Andreea Costinas | 41e0644 | 2020-03-09 09:41:51 +0100 | [diff] [blame] | 1 | // Copyright 2020 The Chromium OS Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include "system-proxy/server_proxy.h" |
| 6 | |
| 7 | #include <iostream> |
| 8 | #include <string> |
| 9 | #include <utility> |
| 10 | #include <vector> |
| 11 | |
| 12 | #include <base/bind.h> |
| 13 | #include <base/bind_helpers.h> |
| 14 | #include <base/callback_helpers.h> |
| 15 | #include <base/posix/eintr_wrapper.h> |
| 16 | #include <base/files/file_util.h> |
| 17 | #include <base/threading/thread.h> |
| 18 | |
| 19 | #include <base/threading/thread_task_runner_handle.h> |
| 20 | |
| 21 | #include "bindings/worker_common.pb.h" |
| 22 | #include "system-proxy/protobuf_util.h" |
| 23 | |
| 24 | namespace system_proxy { |
| 25 | |
| 26 | ServerProxy::ServerProxy(base::OnceClosure quit_closure) |
| 27 | : quit_closure_(std::move(quit_closure)) {} |
| 28 | |
| 29 | void ServerProxy::Init() { |
| 30 | // Start listening for input. |
| 31 | stdin_watcher_ = base::FileDescriptorWatcher::WatchReadable( |
| 32 | STDIN_FILENO, |
| 33 | base::Bind(&ServerProxy::HandleStdinReadable, base::Unretained(this))); |
| 34 | |
| 35 | // Handle termination signals. |
| 36 | signal_handler_.Init(); |
| 37 | for (int signal : {SIGINT, SIGTERM, SIGHUP, SIGQUIT}) { |
| 38 | signal_handler_.RegisterHandler( |
| 39 | signal, base::BindRepeating(&ServerProxy::HandleSignal, |
| 40 | base::Unretained(this))); |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | ServerProxy::~ServerProxy() = default; |
| 45 | |
| 46 | void ServerProxy::HandleStdinReadable() { |
| 47 | WorkerConfigs config; |
| 48 | |
| 49 | if (!ReadProtobuf(STDIN_FILENO, &config)) { |
| 50 | std::string error = "Error decoding protobuf configurations\n"; |
| 51 | base::WriteFileDescriptor(STDERR_FILENO, error.data(), error.size()); |
| 52 | return; |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | bool ServerProxy::HandleSignal(const struct signalfd_siginfo& siginfo) { |
| 57 | base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, |
| 58 | std::move(quit_closure_)); |
| 59 | return true; |
| 60 | } |
| 61 | |
| 62 | } // namespace system_proxy |