• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 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 #include <termios.h>
18 #include <stdlib.h>
19 #include <signal.h>
20 #include <unistd.h>
21 
22 #include <deque>
23 #include <thread>
24 #include <vector>
25 
26 #include <gflags/gflags.h>
27 #include <android-base/logging.h>
28 
29 #include <common/libs/fs/shared_fd.h>
30 #include <common/libs/fs/shared_select.h>
31 #include <host/libs/config/cuttlefish_config.h>
32 #include <host/libs/config/logging.h>
33 
34 DEFINE_int32(console_in_fd,
35              -1,
36              "File descriptor for the console's input channel");
37 DEFINE_int32(console_out_fd,
38              -1,
39              "File descriptor for the console's output channel");
40 
41 namespace cuttlefish {
42 
43 // Handles forwarding the serial console to a pseudo-terminal (PTY)
44 // It receives a couple of fds for the console (could be the same fd twice if,
45 // for example a socket_pair were used).
46 // Data available in the console's output needs to be read immediately to avoid
47 // the having the VMM blocked on writes to the pipe. To achieve this one thread
48 // takes care of (and only of) all read calls (from console output and from the
49 // socket client), using select(2) to ensure it never blocks. Writes are handled
50 // in a different thread, the two threads communicate through a buffer queue
51 // protected by a mutex.
52 class ConsoleForwarder {
53  public:
ConsoleForwarder(std::string console_path,SharedFD console_in,SharedFD console_out,SharedFD console_log)54   ConsoleForwarder(std::string console_path, SharedFD console_in,
55                    SharedFD console_out, SharedFD console_log)
56       : console_path_(console_path),
57         console_in_(console_in),
58         console_out_(console_out),
59         console_log_(console_log) {}
StartServer()60   [[noreturn]] void StartServer() {
61     // Create a new thread to handle writes to the console
62     writer_thread_ = std::thread([this]() { WriteLoop(); });
63     // Use the calling thread (likely the process' main thread) to handle
64     // reading the console's output and input from the client.
65     ReadLoop();
66   }
67  private:
OpenPTY()68   SharedFD OpenPTY() {
69     // Remove any stale symlink to a pts device
70     auto ret = unlink(console_path_.c_str());
71     CHECK(!(ret < 0 && errno != ENOENT))
72         << "Failed to unlink " << console_path_ << ": " << strerror(errno);
73 
74     auto pty = posix_openpt(O_RDWR | O_NOCTTY | O_NONBLOCK);
75     CHECK(pty >= 0) << "Failed to open a PTY: " << strerror(errno);
76 
77     grantpt(pty);
78     unlockpt(pty);
79 
80     // Disable all echo modes on the PTY
81     struct termios termios;
82     CHECK(tcgetattr(pty, &termios) >= 0)
83         << "Failed to get terminal control: " << strerror(errno);
84 
85     termios.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
86     termios.c_oflag &= ~(ONLCR);
87     CHECK(tcsetattr(pty, TCSANOW, &termios) >= 0)
88         << "Failed to set terminal control: " << strerror(errno);
89 
90     auto pty_dev_name = ptsname(pty);
91     CHECK(pty_dev_name != nullptr)
92         << "Failed to obtain PTY device name: " << strerror(errno);
93 
94     CHECK(symlink(pty_dev_name, console_path_.c_str()) >= 0)
95         << "Failed to create symlink to " << pty_dev_name << " at "
96         << console_path_ << ": " << strerror(errno);
97 
98     auto pty_shared_fd = SharedFD::Dup(pty);
99     close(pty);
100     CHECK(pty_shared_fd->IsOpen())
101         << "Error dupping fd " << pty << ": " << pty_shared_fd->StrError();
102 
103     return pty_shared_fd;
104   }
105 
EnqueueWrite(std::shared_ptr<std::vector<char>> buf_ptr,SharedFD fd)106   void EnqueueWrite(std::shared_ptr<std::vector<char>> buf_ptr, SharedFD fd) {
107     std::lock_guard<std::mutex> lock(write_queue_mutex_);
108     write_queue_.emplace_back(fd, buf_ptr);
109     condvar_.notify_one();
110   }
111 
WriteLoop()112   [[noreturn]] void WriteLoop() {
113     while (true) {
114       while (!write_queue_.empty()) {
115         std::shared_ptr<std::vector<char>> buf_ptr;
116         SharedFD fd;
117         {
118           std::lock_guard<std::mutex> lock(write_queue_mutex_);
119           auto& front = write_queue_.front();
120           buf_ptr = front.second;
121           fd = front.first;
122           write_queue_.pop_front();
123         }
124         // Write all bytes to the file descriptor. Writes may block, so the
125         // mutex lock should NOT be held while writing to avoid blocking the
126         // other thread.
127         ssize_t bytes_written = 0;
128         ssize_t bytes_to_write = buf_ptr->size();
129         while (bytes_to_write > 0) {
130           bytes_written =
131               fd->Write(buf_ptr->data() + bytes_written, bytes_to_write);
132           if (bytes_written < 0) {
133             // It is expected for writes to the PTY to fail if nothing is connected
134             if(fd->GetErrno() != EAGAIN) {
135               LOG(ERROR) << "Error writing to fd: " << fd->StrError();
136             }
137 
138             // Don't try to write from this buffer anymore, error handling will
139             // be done on the reading thread (failed client will be
140             // disconnected, on serial console failure this process will abort).
141             break;
142           }
143           bytes_to_write -= bytes_written;
144         }
145       }
146       {
147         std::unique_lock<std::mutex> lock(write_queue_mutex_);
148         // Check again before sleeping, state may have changed
149         if (write_queue_.empty()) {
150           condvar_.wait(lock);
151         }
152       }
153     }
154   }
155 
ReadLoop()156   [[noreturn]] void ReadLoop() {
157     SharedFD client_fd;
158     while (true) {
159       if (!client_fd->IsOpen()) {
160         client_fd = OpenPTY();
161       }
162 
163       SharedFDSet read_set;
164       read_set.Set(console_out_);
165       read_set.Set(client_fd);
166 
167       Select(&read_set, nullptr, nullptr, nullptr);
168       if (read_set.IsSet(console_out_)) {
169         std::shared_ptr<std::vector<char>> buf_ptr = std::make_shared<std::vector<char>>(4096);
170         auto bytes_read = console_out_->Read(buf_ptr->data(), buf_ptr->size());
171         // This is likely unrecoverable, so exit here
172         CHECK(bytes_read > 0) << "Error reading from console output: "
173                               << console_out_->StrError();
174         buf_ptr->resize(bytes_read);
175         EnqueueWrite(buf_ptr, console_log_);
176         if (client_fd->IsOpen()) {
177           EnqueueWrite(buf_ptr, client_fd);
178         }
179       }
180       if (read_set.IsSet(client_fd)) {
181         std::shared_ptr<std::vector<char>> buf_ptr = std::make_shared<std::vector<char>>(4096);
182         auto bytes_read = client_fd->Read(buf_ptr->data(), buf_ptr->size());
183         if (bytes_read <= 0) {
184           // If this happens, it's usually because the PTY controller went away
185           // e.g. the user closed minicom, or killed screen, or closed kgdb. In
186           // such a case, we will just re-create the PTY
187           LOG(ERROR) << "Error reading from client fd: "
188                      << client_fd->StrError();
189           client_fd->Close();
190         } else {
191           buf_ptr->resize(bytes_read);
192           EnqueueWrite(buf_ptr, console_in_);
193         }
194       }
195     }
196   }
197 
198   std::string console_path_;
199   SharedFD console_in_;
200   SharedFD console_out_;
201   SharedFD console_log_;
202   std::thread writer_thread_;
203   std::mutex write_queue_mutex_;
204   std::condition_variable condvar_;
205   std::deque<std::pair<SharedFD, std::shared_ptr<std::vector<char>>>>
206       write_queue_;
207 };
208 
ConsoleForwarderMain(int argc,char ** argv)209 int ConsoleForwarderMain(int argc, char** argv) {
210   DefaultSubprocessLogging(argv);
211   ::gflags::ParseCommandLineFlags(&argc, &argv, true);
212 
213   CHECK(!(FLAGS_console_in_fd < 0 || FLAGS_console_out_fd < 0))
214       << "Invalid file descriptors: " << FLAGS_console_in_fd << ", "
215       << FLAGS_console_out_fd;
216 
217   auto console_in = SharedFD::Dup(FLAGS_console_in_fd);
218   CHECK(console_in->IsOpen()) << "Error dupping fd " << FLAGS_console_in_fd
219                               << ": " << console_in->StrError();
220   close(FLAGS_console_in_fd);
221 
222   auto console_out = SharedFD::Dup(FLAGS_console_out_fd);
223   CHECK(console_out->IsOpen()) << "Error dupping fd " << FLAGS_console_out_fd
224                                << ": " << console_out->StrError();
225   close(FLAGS_console_out_fd);
226 
227   auto config = CuttlefishConfig::Get();
228   CHECK(config) << "Unable to get config object";
229 
230   auto instance = config->ForDefaultInstance();
231   auto console_path = instance.console_path();
232   auto console_log = instance.PerInstancePath("console_log");
233   auto console_log_fd =
234       SharedFD::Open(console_log.c_str(), O_CREAT | O_APPEND | O_WRONLY, 0666);
235   ConsoleForwarder console_forwarder(console_path, console_in, console_out, console_log_fd);
236 
237   // Don't get a SIGPIPE from the clients
238   CHECK(sigaction(SIGPIPE, nullptr, nullptr) == 0)
239       << "Failed to set SIGPIPE to be ignored: " << strerror(errno);
240 
241   console_forwarder.StartServer();
242 }
243 
244 }  // namespace cuttlefish
245 
main(int argc,char ** argv)246 int main(int argc, char** argv) {
247   return cuttlefish::ConsoleForwarderMain(argc, argv);
248 }
249