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