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 // TODO: We can't use std::shared_ptr on the older guests due to HALs.
18 
19 #ifndef CUTTLEFISH_COMMON_COMMON_LIBS_FS_SHARED_FD_H_
20 #define CUTTLEFISH_COMMON_COMMON_LIBS_FS_SHARED_FD_H_
21 
22 #ifdef __linux__
23 #include <sys/epoll.h>
24 #include <sys/eventfd.h>
25 #endif
26 #include <sys/inotify.h>
27 #include <sys/ioctl.h>
28 #include <sys/mman.h>
29 #include <sys/select.h>
30 #include <sys/socket.h>
31 #include <sys/stat.h>
32 #include <sys/time.h>
33 #include <sys/types.h>
34 #include <sys/uio.h>
35 #include <sys/un.h>
36 
37 #include <chrono>
38 #include <memory>
39 #include <sstream>
40 #include <string>
41 #include <utility>
42 #include <vector>
43 
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <string.h>
47 #include <termios.h>
48 #include <unistd.h>
49 
50 #include <android-base/cmsg.h>
51 
52 #ifdef __linux__
53 #include <linux/vm_sockets.h>
54 #endif
55 
56 #include "common/libs/utils/result.h"
57 
58 /**
59  * Classes to to enable safe access to files.
60  * POSIX kernels have an unfortunate habit of recycling file descriptors.
61  * That can cause problems like http://b/26121457 in code that doesn't manage
62  * file lifetimes properly. These classes implement an alternate interface
63  * that has some advantages:
64  *
65  * o References to files are tightly controlled
66  * o Files are auto-closed if they go out of scope
67  * o Files are life-time aware. It is impossible to close the instance twice.
68  * o File descriptors are always initialized. By default the descriptor is
69  *   set to a closed instance.
70  *
71  * These classes are designed to mimic to POSIX interface as closely as
72  * possible. Specifically, they don't attempt to track the type of file
73  * descriptors and expose only the valid operations. This is by design, since
74  * it makes it easier to convert existing code to SharedFDs and avoids the
75  * possibility that new POSIX functionality will lead to large refactorings.
76  */
77 namespace cuttlefish {
78 
79 struct PollSharedFd;
80 class Epoll;
81 class FileInstance;
82 struct VhostUserVsockCid;
83 struct VsockCid;
84 
85 /**
86  * Counted reference to a FileInstance.
87  *
88  * This is also the place where most new FileInstances are created. The creation
89  * methods correspond to the underlying POSIX calls.
90  *
91  * SharedFDs can be compared and stored in STL containers. The semantics are
92  * slightly different from POSIX file descriptors:
93  *
94  * o The value of the SharedFD is the identity of its underlying FileInstance.
95  *
96  * o Each newly created SharedFD has a unique, closed FileInstance:
97  *    SharedFD a, b;
98  *    assert (a != b);
99  *    a = b;
100  *    assert(a == b);
101  *
102  * o The identity of the FileInstance is not affected by closing the file:
103  *   SharedFD a, b;
104  *   set<SharedFD> s;
105  *   s.insert(a);
106  *   assert(s.count(a) == 1);
107  *   assert(s.count(b) == 0);
108  *   a->Close();
109  *   assert(s.count(a) == 1);
110  *   assert(s.count(b) == 0);
111  *
112  * o FileInstances are never visibly recycled.
113  *
114  * o If all of the SharedFDs referring to a FileInstance go out of scope the
115  *   file is closed and the FileInstance is recycled.
116  *
117  * Creation methods must ensure that no references to the new file descriptor
118  * escape. The underlying FileInstance should have the only reference to the
119  * file descriptor. Any method that needs to know the fd must be in either
120  * SharedFD or FileInstance.
121  *
122  * SharedFDs always have an underlying FileInstance, so all of the method
123  * calls are safe in accordance with the null object pattern.
124  *
125  * Errors on system calls that create new FileInstances, such as Open, are
126  * reported with a new, closed FileInstance with the errno set.
127  */
128 class SharedFD {
129   // Give WeakFD access to the underlying shared_ptr.
130   friend class WeakFD;
131  public:
132   inline SharedFD();
SharedFD(const std::shared_ptr<FileInstance> & in)133   SharedFD(const std::shared_ptr<FileInstance>& in) : value_(in) {}
134   SharedFD(SharedFD const&) = default;
135   SharedFD(SharedFD&& other);
136   SharedFD& operator=(SharedFD const&) = default;
137   SharedFD& operator=(SharedFD&& other);
138   // Reference the listener as a FileInstance to make this FD type agnostic.
139   static SharedFD Accept(const FileInstance& listener, struct sockaddr* addr,
140                          socklen_t* addrlen);
141   static SharedFD Accept(const FileInstance& listener);
142   static SharedFD Dup(int unmanaged_fd);
143   // All SharedFDs have the O_CLOEXEC flag after creation. To remove use the
144   // Fcntl or Dup functions.
145   static SharedFD Open(const char* pathname, int flags, mode_t mode = 0);
146   static SharedFD Open(const std::string& pathname, int flags, mode_t mode = 0);
147   static SharedFD InotifyFd();
148   static SharedFD Creat(const std::string& pathname, mode_t mode);
149   static int Fchdir(SharedFD);
150   static Result<SharedFD> Fifo(const std::string& pathname, mode_t mode);
151   static bool Pipe(SharedFD* fd0, SharedFD* fd1);
152 #ifdef __linux__
153   static SharedFD Event(int initval = 0, int flags = 0);
154 #endif
155   static SharedFD MemfdCreate(const std::string& name, unsigned int flags = 0);
156   static SharedFD MemfdCreateWithData(const std::string& name, const std::string& data, unsigned int flags = 0);
157   static SharedFD Mkstemp(std::string* path);
158   static int Poll(PollSharedFd* fds, size_t num_fds, int timeout);
159   static int Poll(std::vector<PollSharedFd>& fds, int timeout);
160   static bool SocketPair(int domain, int type, int protocol, SharedFD* fd0,
161                          SharedFD* fd1);
162   static Result<std::pair<SharedFD, SharedFD>> SocketPair(int domain, int type,
163                                                           int protocol);
164   static SharedFD Socket(int domain, int socket_type, int protocol);
165   static SharedFD SocketLocalClient(const std::string& name, bool is_abstract,
166                                     int in_type);
167   static SharedFD SocketLocalClient(const std::string& name, bool is_abstract,
168                                     int in_type, int timeout_seconds);
169   static SharedFD SocketLocalClient(int port, int type);
170   static SharedFD SocketClient(const std::string& host, int port,
171                                int type, std::chrono::seconds timeout = std::chrono::seconds(0));
172   static SharedFD Socket6Client(const std::string& host, const std::string& interface, int port,
173                                 int type, std::chrono::seconds timeout = std::chrono::seconds(0));
174   static SharedFD SocketLocalServer(const std::string& name, bool is_abstract,
175                                     int in_type, mode_t mode);
176   static SharedFD SocketLocalServer(int port, int type);
177 
178 #ifdef __linux__
179   // For binding in vsock, svm_cid from `cid` param would be either
180   // VMADDR_CID_ANY, VMADDR_CID_LOCAL, VMADDR_CID_HOST or their own CID, and it
181   // is used for indicating connections which it accepts from.
182   //  * VMADDR_CID_ANY: accept from any
183   //  * VMADDR_CID_LOCAL: accept from local
184   //  * VMADDR_CID_HOST: accept from child vm
185   //  * their own CID: accept from parent vm
186   // With vhost-user-vsock, it is basically similar to VMADDR_CID_HOST, but for
187   // now it has limitations that it should bind to a specific socket file which
188   // is for a certain cid. So for vhost-user-vsock, we need to specify the
189   // expected client's cid. That's why vhost_user_vsock_listening_cid is
190   // necessary.
191   // TODO: combining them when vhost-user-vsock impl supports a kind of
192   // VMADDR_CID_HOST
193   static SharedFD VsockServer(unsigned int port, int type,
194                               std::optional<int> vhost_user_vsock_listening_cid,
195                               unsigned int cid = VMADDR_CID_ANY);
196   static SharedFD VsockServer(
197       int type, std::optional<int> vhost_user_vsock_listening_cid);
198   static SharedFD VsockClient(unsigned int cid, unsigned int port, int type,
199                               bool vhost_user);
200 #endif
201 
202   bool operator==(const SharedFD& rhs) const { return value_ == rhs.value_; }
203 
204   bool operator!=(const SharedFD& rhs) const { return value_ != rhs.value_; }
205 
206   bool operator<(const SharedFD& rhs) const { return value_ < rhs.value_; }
207 
208   bool operator<=(const SharedFD& rhs) const { return value_ <= rhs.value_; }
209 
210   bool operator>(const SharedFD& rhs) const { return value_ > rhs.value_; }
211 
212   bool operator>=(const SharedFD& rhs) const { return value_ >= rhs.value_; }
213 
214   std::shared_ptr<FileInstance> operator->() const { return value_; }
215 
216   const FileInstance& operator*() const { return *value_; }
217 
218   FileInstance& operator*() { return *value_; }
219 
220  private:
221   static SharedFD ErrorFD(int error);
222 
223   std::shared_ptr<FileInstance> value_;
224 };
225 
226 /**
227  * A non-owning reference to a FileInstance. The referenced FileInstance needs
228  * to be managed by a SharedFD. A WeakFD needs to be converted to a SharedFD to
229  * access the underlying FileInstance.
230  */
231 class WeakFD {
232  public:
WeakFD(SharedFD shared_fd)233   WeakFD(SharedFD shared_fd) : value_(shared_fd.value_) {}
234 
235   // Creates a new SharedFD object that shares ownership of the underlying fd.
236   // Callers need to check that the returned SharedFD is open before using it.
237   SharedFD lock() const;
238 
239  private:
240   std::weak_ptr<FileInstance> value_;
241 };
242 
243 // Provides RAII semantics for memory mappings, preventing memory leaks. It does
244 // not however prevent use-after-free errors since the underlying pointer can be
245 // extracted and could survive this object.
246 class ScopedMMap {
247  public:
248   ScopedMMap();
249   ScopedMMap(void* ptr, size_t size);
250   ScopedMMap(const ScopedMMap& other) = delete;
251   ScopedMMap& operator=(const ScopedMMap& other) = delete;
252   ScopedMMap(ScopedMMap&& other);
253 
254   ~ScopedMMap();
255 
get()256   void* get() { return ptr_; }
get()257   const void* get() const { return ptr_; }
len()258   size_t len() const { return len_; }
259 
260   operator bool() const { return ptr_ != MAP_FAILED; }
261 
262   // Checks whether the interval [offset, offset + length) is contained within
263   // [0, len_)
WithinBounds(size_t offset,size_t length)264   bool WithinBounds(size_t offset, size_t length) const {
265     // Don't add offset + len to avoid overflow
266     return offset < len_ && len_ - offset >= length;
267   }
268 
269  private:
270   void* ptr_ = MAP_FAILED;
271   size_t len_;
272 };
273 
274 /**
275  * Tracks the lifetime of a file descriptor and provides methods to allow
276  * callers to use the file without knowledge of the underlying descriptor
277  * number.
278  *
279  * FileInstances have two states: Open and Closed. They may start in either
280  * state. However, once a FileIntance enters the Closed state it cannot be
281  * reopened.
282  *
283  * Construction of FileInstances is limited to select classes to avoid
284  * escaping file descriptors. At this point SharedFD is the only class
285  * that has access. We may eventually have ScopedFD and WeakFD.
286  */
287 class FileInstance {
288   // Give SharedFD access to the aliasing constructor.
289   friend class SharedFD;
290   friend class Epoll;
291 
292  public:
~FileInstance()293   virtual ~FileInstance() { Close(); }
294 
295   // This can't be a singleton because our shared_ptr's aren't thread safe.
296   static std::shared_ptr<FileInstance> ClosedInstance();
297 
298   int Bind(const struct sockaddr* addr, socklen_t addrlen);
299   int Connect(const struct sockaddr* addr, socklen_t addrlen);
300   int ConnectWithTimeout(const struct sockaddr* addr, socklen_t addrlen,
301                          struct timeval* timeout);
302   void Close();
303 
304   bool Chmod(mode_t mode);
305 
306   // Returns true if the entire input was copied.
307   // Otherwise an error will be set either on this file or the input.
308   // The non-const reference is needed to avoid binding this to a particular
309   // reference type.
310   bool CopyFrom(FileInstance& in, size_t length, FileInstance* stop = nullptr);
311   // Same as CopyFrom, but reads from input until EOF is reached.
312   bool CopyAllFrom(FileInstance& in, FileInstance* stop = nullptr);
313 
314   int UNMANAGED_Dup();
315   int UNMANAGED_Dup2(int newfd);
316   int Fchdir();
317   int Fcntl(int command, int value);
318   int Fsync();
319 
320   Result<void> Flock(int operation);
321 
GetErrno()322   int GetErrno() const { return errno_; }
323   int GetSockName(struct sockaddr* addr, socklen_t* addrlen);
324 
325 #ifdef __linux__
326   unsigned int VsockServerPort();
327 #endif
328 
329   int Ioctl(int request, void* val = nullptr);
IsOpen()330   bool IsOpen() const { return fd_ != -1; }
331 
332   // in probably isn't modified, but the API spec doesn't have const.
333   bool IsSet(fd_set* in) const;
334 
335   // whether this is a regular file or not
IsRegular()336   bool IsRegular() const { return is_regular_file_; }
337 
338   /**
339    * Adds a hard link to a file descriptor, based on the current working
340    * directory of the process or to some absolute path.
341    *
342    * https://www.man7.org/linux/man-pages/man2/linkat.2.html
343    *
344    * Using this on a file opened with O_TMPFILE can link it into the filesystem.
345    */
346   // Used with O_TMPFILE files to attach them to the filesystem.
347   int LinkAtCwd(const std::string& path);
348   int Listen(int backlog);
349   static void Log(const char* message);
350   off_t LSeek(off_t offset, int whence);
351   ssize_t Recv(void* buf, size_t len, int flags);
352   ssize_t RecvMsg(struct msghdr* msg, int flags);
353   ssize_t Read(void* buf, size_t count);
354 #ifdef __linux__
355   int EventfdRead(eventfd_t* value);
356 #endif
357   ssize_t Send(const void* buf, size_t len, int flags);
358   ssize_t SendMsg(const struct msghdr* msg, int flags);
359 
360   template <typename... Args>
SendFileDescriptors(const void * buf,size_t len,Args &&...sent_fds)361   ssize_t SendFileDescriptors(const void* buf, size_t len, Args&&... sent_fds) {
362     std::vector<int> fds;
363     android::base::Append(fds, std::forward<int>(sent_fds->fd_)...);
364     errno = 0;
365     auto ret = android::base::SendFileDescriptorVector(fd_, buf, len, fds);
366     errno_ = errno;
367     return ret;
368   }
369 
370   int Shutdown(int how);
371   void Set(fd_set* dest, int* max_index) const;
372   int SetSockOpt(int level, int optname, const void* optval, socklen_t optlen);
373   int GetSockOpt(int level, int optname, void* optval, socklen_t* optlen);
374   int SetTerminalRaw();
375   std::string StrError() const;
376   ScopedMMap MMap(void* addr, size_t length, int prot, int flags, off_t offset);
377   ssize_t Truncate(off_t length);
378   /*
379    * If the file is a regular file and the count is 0, Write() may detect
380    * error(s) by calling write(fd, buf, 0) declared in <unistd.h>. If detected,
381    * it will return -1. If not, 0 will be returned. For non-regular files such
382    * as socket or pipe, write(fd, buf, 0) is not specified. Write(), however,
383    * will do nothing and just return 0.
384    *
385    */
386   ssize_t Write(const void* buf, size_t count);
387 #ifdef __linux__
388   int EventfdWrite(eventfd_t value);
389 #endif
390   bool IsATTY();
391 
392   int Futimens(const struct timespec times[2]);
393 
394   // Returns the target of "/proc/getpid()/fd/" + std::to_string(fd_)
395   // if appropriate
396   Result<std::string> ProcFdLinkTarget() const;
397 
398   // inotify related functions
399   int InotifyAddWatch(const std::string& pathname, uint32_t mask);
400   void InotifyRmWatch(int watch);
401 
402  private:
403   FileInstance(int fd, int in_errno);
404   FileInstance* Accept(struct sockaddr* addr, socklen_t* addrlen) const;
405 
406   int fd_;
407   int errno_;
408   std::string identity_;
409   bool is_regular_file_;
410 };
411 
412 struct PollSharedFd {
413   SharedFD fd;
414   short events;
415   short revents;
416 };
417 
418 /* Methods that need both a fully defined SharedFD and a fully defined
419    FileInstance. */
420 
SharedFD()421 SharedFD::SharedFD() : value_(FileInstance::ClosedInstance()) {}
422 
423 }  // namespace cuttlefish
424 
425 #endif  // CUTTLEFISH_COMMON_COMMON_LIBS_FS_SHARED_FD_H_
426