Android-cuttlefish cvd tool
fd.h
Go to the documentation of this file.
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
17#ifndef CUTTLEFISH_COMMON_COMMON_LIBS_FS_FILE_INSTANCE_H_
18#define CUTTLEFISH_COMMON_COMMON_LIBS_FS_FILE_INSTANCE_H_
19
20#include <errno.h>
21#include <fcntl.h>
22#include <stddef.h>
23#include <stdint.h>
24#include <string.h>
25#include <sys/inotify.h>
26#include <sys/ioctl.h>
27#include <sys/mman.h>
28#include <sys/select.h>
29#include <sys/socket.h>
30#include <sys/stat.h>
31#include <sys/time.h>
32#include <sys/types.h>
33#include <sys/uio.h>
34#include <sys/un.h>
35#include <termios.h>
36#include <unistd.h>
37
38// Must be below sys/socket.h to support older libc
39#ifdef __linux__
40#include <linux/vm_sockets.h>
41#include <sys/epoll.h>
42#include <sys/eventfd.h>
43#endif
44
45#include <chrono>
46#include <memory>
47#include <string>
48#include <string_view>
49#include <vector>
50
51#include "android-base/cmsg.h"
52
54#include "cuttlefish/io/io.h"
56
76namespace cuttlefish {
88class Fd : public ReaderWriterSeeker {
89 // Give SharedFD access to the aliasing constructor.
90 friend class SharedFD;
91 friend class Fd;
92 friend class Epoll;
93
94 public:
95 Fd();
96 Fd(Fd&) = delete;
97 Fd(Fd&&);
98 ~Fd();
99 Fd& operator=(Fd&) = delete;
100 Fd& operator=(Fd&&);
101
102 // All Fds have the O_CLOEXEC flag after creation. To remove use the
103 // Fcntl or Dup functions.
104
105 static Result<Fd> Accept(const Fd& listener);
106 static Result<Fd> Creat(std::string_view path, mode_t mode);
107 static Result<Fd> Dup(int unmanaged_fd);
108 static Result<Fd> Fifo(std::string_view pathname, mode_t mode);
109 static Result<Fd> MemfdCreate(std::string_view name, unsigned int flags = 0);
110 static Result<std::pair<Fd, std::string>> Mkostemp(std::string_view path,
111 int flags = O_CLOEXEC);
112 static Result<Fd> Open(std::string_view pathname, int flags, mode_t mode = 0);
114 static Result<std::pair<Fd, Fd>> SocketPair(int domain, int type,
115 int protocol);
116 static Result<Fd> Socket(int domain, int socket_type, int protocol);
118 std::string_view host, std::string_view interface, int port, int type,
119 std::chrono::seconds timeout = std::chrono::seconds(0));
121 std::string_view host, int port, int type,
122 std::chrono::seconds timeout = std::chrono::seconds(0));
123 static Result<Fd> SocketLocalClient(std::string_view name, bool is_abstract,
124 int in_type);
125 static Result<Fd> SocketLocalClient(std::string_view name, bool is_abstract,
126 int in_type, int timeout_seconds);
127 static Result<Fd> SocketLocalClient(int port, int type);
128 static Result<Fd> SocketLocalServer(std::string_view name, bool is_abstract,
129 int in_type, mode_t mode);
130 static Result<Fd> SocketLocalServer(int port, int type);
131
132#ifdef __linux__
133 static Result<Fd> Event(int initval = 0, int flags = 0);
134 static Result<Fd> InotifyFd();
135 static Result<Fd> ShmOpen(std::string_view name, int oflag, int mode);
136 // For binding in vsock, svm_cid from `cid` param would be either
137 // VMADDR_CID_ANY, VMADDR_CID_LOCAL, VMADDR_CID_HOST or their own CID, and it
138 // is used for indicating connections which it accepts from.
139 // * VMADDR_CID_ANY: accept from any
140 // * VMADDR_CID_LOCAL: accept from local
141 // * VMADDR_CID_HOST: accept from child vm
142 // * their own CID: accept from parent vm
143 // With vhost-user-vsock, it is basically similar to VMADDR_CID_HOST, but for
144 // now it has limitations that it should bind to a specific socket file which
145 // is for a certain cid. So for vhost-user-vsock, we need to specify the
146 // expected client's cid. That's why vhost_user_vsock_listening_cid is
147 // necessary.
148 // TODO: combining them when vhost-user-vsock impl supports a kind of
149 // VMADDR_CID_HOST
150 static std::string GetVhostUserVsockServerAddr(
151 unsigned int port, int vhost_user_vsock_listening_cid);
152 static std::string GetVhostUserVsockClientAddr(int cid);
153 static Result<Fd> VsockServer(
154 unsigned int port, int type,
155 std::optional<int> vhost_user_vsock_listening_cid,
156 unsigned int cid = VMADDR_CID_ANY);
157 static Result<Fd> VsockServer(
158 int type, std::optional<int> vhost_user_vsock_listening_cid);
159#endif
160
161 int Bind(const struct sockaddr* addr, socklen_t addrlen);
162 int Connect(const struct sockaddr* addr, socklen_t addrlen);
163 int ConnectWithTimeout(const struct sockaddr* addr, socklen_t addrlen,
164 struct timeval* timeout);
165 void Close();
166
167 bool Chmod(mode_t mode);
168
169 // Returns true if the entire input was copied.
170 // Otherwise an error will be set either on this file or the input.
171 // The non-const reference is needed to avoid binding this to a particular
172 // reference type.
173 bool CopyFrom(Fd& in, size_t length, Fd* stop = nullptr);
174 // Same as CopyFrom, but reads from input until EOF is reached.
175 bool CopyAllFrom(Fd& in, Fd* stop = nullptr);
176 bool SendFile(Fd& in, off_t* offset, size_t count);
177
178 int UNMANAGED_Dup();
179 int UNMANAGED_Dup2(int newfd);
180 int Fchdir();
181 int Fcntl(int command, int value);
182 int Fsync();
183
184 Result<void> Flock(int operation);
185
186 int GetErrno() const { return errno_; }
187 int GetSockName(struct sockaddr* addr, socklen_t* addrlen);
188
189#ifdef __linux__
190 unsigned int VsockServerPort();
191#endif
192
193 int Ioctl(int request, void* val = nullptr);
194 bool IsOpen() const { return fd_ != -1; }
195
196 // in probably isn't modified, but the API spec doesn't have const.
197 bool IsSet(fd_set* in) const;
198
199 // whether this is a regular file or not
200 bool IsRegular() const { return is_regular_file_; }
201
210 // Used with O_TMPFILE files to attach them to the filesystem.
211 int LinkAtCwd(const std::string& path);
212 int Listen(int backlog);
213 static void Log(const char* message);
214 off_t LSeek(off_t offset, int whence);
215 ssize_t Recv(void* buf, size_t len, int flags);
216 ssize_t RecvMsg(struct msghdr* msg, int flags);
217 Result<uint64_t> Read(void* buf, uint64_t count) override;
218 Result<uint64_t> PRead(void* buf, uint64_t count,
219 uint64_t offset) const override;
220#ifdef __linux__
221 int EventfdRead(eventfd_t* value);
222#endif
223 ssize_t Send(const void* buf, size_t len, int flags);
224 ssize_t SendMsg(const struct msghdr* msg, int flags);
225
226 Result<uint64_t> SeekSet(uint64_t) override;
227 Result<uint64_t> SeekCur(int64_t) override;
228 Result<uint64_t> SeekEnd(int64_t) override;
229
230 template <typename... Args>
231 ssize_t SendFileDescriptors(const void* buf, size_t len, Args&&... sent_fds) {
232 std::vector<int> fds;
233 (fds.push_back(sent_fds->fd_), ...);
234 errno = 0;
235 auto ret = android::base::SendFileDescriptorVector(fd_, buf, len, fds);
236 errno_ = errno;
237 return ret;
238 }
239
240 int Shutdown(int how);
241 void Set(fd_set* dest, int* max_index) const;
242 int SetSockOpt(int level, int optname, const void* optval, socklen_t optlen);
243 int GetSockOpt(int level, int optname, void* optval, socklen_t* optlen);
244 int SetTerminalRaw();
245 std::string StrError() const;
246 ScopedMMap MMap(void* addr, size_t length, int prot, int flags, off_t offset);
247 Result<void> Truncate(uint64_t length) override;
248 /*
249 * If the file is a regular file and the count is 0, Write() may detect
250 * error(s) by calling write(fd, buf, 0) declared in <unistd.h>. If detected,
251 * it will return -1. If not, 0 will be returned. For non-regular files such
252 * as socket or pipe, write(fd, buf, 0) is not specified. Write(), however,
253 * will do nothing and just return 0.
254 *
255 */
256 Result<uint64_t> Write(const void* buf, uint64_t count) override;
257 Result<uint64_t> PWrite(const void* buf, uint64_t count,
258 uint64_t offset) override;
259#ifdef __linux__
260 int EventfdWrite(eventfd_t value);
261#endif
262 bool IsATTY();
263
264 int Futimens(const struct timespec times[2]);
265
266 // inotify related functions
267 int InotifyAddWatch(const std::string& pathname, uint32_t mask);
268 void InotifyRmWatch(int watch);
269
270 private:
271 Fd(int fd, int in_errno);
272
273 static Fd ErrorFD(int error);
274
275 int fd_;
277 std::string identity_;
279};
280
281} // namespace cuttlefish
282
283#endif // CUTTLEFISH_COMMON_COMMON_LIBS_FS_FILE_INSTANCE_H_
Definition: epoll.h:35
Definition: fd.h:88
bool IsRegular() const
Definition: fd.h:200
static Result< Fd > Fifo(std::string_view pathname, mode_t mode)
Definition: fd.cc:214
static Result< Fd > Socket(int domain, int socket_type, int protocol)
Definition: fd.cc:228
int errno_
Definition: fd.h:276
int Shutdown(int how)
Definition: fd.cc:812
int Ioctl(int request, void *val=nullptr)
Definition: fd.cc:717
int Connect(const struct sockaddr *addr, socklen_t addrlen)
Definition: fd.cc:655
static Result< std::pair< Fd, Fd > > SocketPair(int domain, int type, int protocol)
Definition: fd.cc:187
ssize_t Send(const void *buf, size_t len, int flags)
Definition: fd.cc:782
static Fd ErrorFD(int error)
Definition: fd.cc:245
int Fcntl(int command, int value)
Definition: fd.cc:682
Result< uint64_t > SeekEnd(int64_t) override
Definition: fd.cc:806
int Futimens(const struct timespec times[2])
Definition: fd.cc:914
int UNMANAGED_Dup2(int newfd)
Definition: fd.cc:667
Result< uint64_t > Read(void *buf, uint64_t count) override
Definition: fd.cc:756
static void Log(const char *message)
Definition: fd.cc:636
static Result< Fd > SocketLocalClient(std::string_view name, bool is_abstract, int in_type)
Definition: fd.cc:247
int ConnectWithTimeout(const struct sockaddr *addr, socklen_t addrlen, struct timeval *timeout)
Definition: fd.cc:563
bool CopyFrom(Fd &in, size_t length, Fd *stop=nullptr)
Definition: fd.cc:446
int fd_
Definition: fd.h:275
ssize_t SendMsg(const struct msghdr *msg, int flags)
Definition: fd.cc:788
Fd(Fd &)=delete
int SetTerminalRaw()
Definition: fd.cc:831
int SetSockOpt(int level, int optname, const void *optval, socklen_t optlen)
Definition: fd.cc:818
int Bind(const struct sockaddr *addr, socklen_t addrlen)
Definition: fd.cc:649
bool SendFile(Fd &in, off_t *offset, size_t count)
Definition: fd.cc:512
void Close()
Definition: fd.cc:535
std::string identity_
Definition: fd.h:277
std::string StrError() const
Definition: fd.cc:856
friend class Fd
Definition: fd.h:91
bool IsOpen() const
Definition: fd.h:194
Result< uint64_t > Write(const void *buf, uint64_t count) override
Definition: fd.cc:878
int UNMANAGED_Dup()
Definition: fd.cc:661
bool IsATTY()
Definition: fd.cc:908
int Fchdir()
Definition: fd.cc:673
Result< uint64_t > SeekSet(uint64_t) override
Definition: fd.cc:794
Result< uint64_t > SeekCur(int64_t) override
Definition: fd.cc:800
int Listen(int backlog)
Definition: fd.cc:732
Fd & operator=(Fd &)=delete
int InotifyAddWatch(const std::string &pathname, uint32_t mask)
Definition: fd.cc:921
static Result< std::pair< Fd, std::string > > Mkostemp(std::string_view path, int flags=O_CLOEXEC)
Definition: fd.cc:235
static Result< Fd > Open(std::string_view pathname, int flags, mode_t mode=0)
Definition: fd.cc:195
bool is_regular_file_
Definition: fd.h:278
static Result< Fd > SocketClient(std::string_view host, int port, int type, std::chrono::seconds timeout=std::chrono::seconds(0))
Definition: fd.cc:283
ScopedMMap MMap(void *addr, size_t length, int prot, int flags, off_t offset)
Definition: fd.cc:861
bool Chmod(mode_t mode)
Definition: fd.cc:557
static Result< std::pair< Fd, Fd > > Pipe()
Definition: fd.cc:153
static Result< Fd > MemfdCreate(std::string_view name, unsigned int flags=0)
Definition: fd.cc:183
int GetSockOpt(int level, int optname, void *optval, socklen_t *optlen)
Definition: fd.cc:825
Result< void > Truncate(uint64_t length) override
Definition: fd.cc:869
int LinkAtCwd(const std::string &path)
Definition: fd.cc:723
Result< uint64_t > PWrite(const void *buf, uint64_t count, uint64_t offset) override
Definition: fd.cc:891
static Result< Fd > Socket6Client(std::string_view host, std::string_view interface, int port, int type, std::chrono::seconds timeout=std::chrono::seconds(0))
Definition: fd.cc:300
int GetSockName(struct sockaddr *addr, socklen_t *addrlen)
Definition: fd.cc:702
Result< uint64_t > PRead(void *buf, uint64_t count, uint64_t offset) const override
Definition: fd.cc:765
int Fsync()
Definition: fd.cc:688
bool IsSet(fd_set *in) const
Definition: fd.cc:626
off_t LSeek(off_t offset, int whence)
Definition: fd.cc:738
ssize_t SendFileDescriptors(const void *buf, size_t len, Args &&... sent_fds)
Definition: fd.h:231
void Set(fd_set *dest, int *max_index) const
Definition: fd.cc:639
void InotifyRmWatch(int watch)
Definition: fd.cc:925
ssize_t RecvMsg(struct msghdr *msg, int flags)
Definition: fd.cc:750
~Fd()
Definition: fd.cc:130
static Result< Fd > Creat(std::string_view path, mode_t mode)
Definition: fd.cc:210
static Result< Fd > Accept(const Fd &listener)
Definition: fd.cc:139
static Result< Fd > Dup(int unmanaged_fd)
Definition: fd.cc:146
ssize_t Recv(void *buf, size_t len, int flags)
Definition: fd.cc:744
bool CopyAllFrom(Fd &in, Fd *stop=nullptr)
Definition: fd.cc:501
static Result< Fd > SocketLocalServer(std::string_view name, bool is_abstract, int in_type, mode_t mode)
Definition: fd.cc:359
Result< void > Flock(int operation)
Definition: fd.cc:694
int GetErrno() const
Definition: fd.h:186
Definition: scoped_mmap.h:28
Definition: shared_fd.h:124
#define error(format, args...)
Definition: fec_private.h:201
char * name
Definition: libf2fs.c:1403
ssize_t SendFileDescriptorVector(borrowed_fd sockfd, const void *data, size_t len, const std::vector< int > &fds)
Definition: cmsg.cpp:32
Event
Definition: kernel_log_server.h:31
Definition: alloc_driver.h:20
tl::expected< T, StackTraceError > Result
Definition: result_type.h:30
std::vector< std::string_view > Args
Definition: incremental.h:28
__u32 mask
Definition: nl80211.h:0
uint8_t type
Definition: pairing_connection.h:0