Kevin Cernekee | 27bcaa6 | 2016-12-03 11:16:26 -0800 | [diff] [blame] | 1 | // Copyright 2016 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 | |
Hidehiko Abe | 3a7e513 | 2018-02-15 13:07:50 +0900 | [diff] [blame] | 5 | #include "arc/network/helper_process.h" |
Kevin Cernekee | 27bcaa6 | 2016-12-03 11:16:26 -0800 | [diff] [blame] | 6 | |
| 7 | #include <signal.h> |
| 8 | #include <string.h> |
| 9 | #include <sys/socket.h> |
| 10 | #include <unistd.h> |
| 11 | |
| 12 | #include <utility> |
| 13 | #include <vector> |
| 14 | |
| 15 | #include <base/logging.h> |
| 16 | #include <base/process/launch.h> |
| 17 | #include <brillo/syslog_logging.h> |
| 18 | |
| 19 | namespace arc_networkd { |
| 20 | |
| 21 | void HelperProcess::Start(int argc, char* argv[], const std::string& fd_arg) { |
| 22 | int control[2]; |
| 23 | |
| 24 | if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, control) != 0) { |
| 25 | PLOG(FATAL) << "socketpair failed"; |
| 26 | } |
| 27 | |
Taoyu Li | af944c9 | 2019-10-01 12:22:31 +0900 | [diff] [blame] | 28 | base::ScopedFD control_fd(control[0]); |
| 29 | msg_dispatcher_ = |
| 30 | std::make_unique<MessageDispatcher>(std::move(control_fd), false); |
Kevin Cernekee | 27bcaa6 | 2016-12-03 11:16:26 -0800 | [diff] [blame] | 31 | const int subprocess_fd = control[1]; |
| 32 | |
| 33 | CHECK_GE(argc, 1); |
| 34 | std::vector<std::string> child_argv; |
| 35 | for (int i = 0; i < argc; i++) { |
| 36 | child_argv.push_back(argv[i]); |
| 37 | } |
| 38 | child_argv.push_back(fd_arg + "=" + std::to_string(subprocess_fd)); |
| 39 | |
| 40 | base::FileHandleMappingVector fd_mapping; |
| 41 | fd_mapping.push_back({subprocess_fd, subprocess_fd}); |
| 42 | |
| 43 | base::LaunchOptions options; |
Qijiang Fan | de93b8e | 2019-10-30 14:59:50 +0900 | [diff] [blame] | 44 | // TODO(fqj): change to std::move(fd_mapping) |
| 45 | options.fds_to_remap = FDS_TO_REMAP(fd_mapping); |
Kevin Cernekee | 27bcaa6 | 2016-12-03 11:16:26 -0800 | [diff] [blame] | 46 | |
| 47 | base::Process p = base::LaunchProcess(child_argv, options); |
| 48 | CHECK(p.IsValid()); |
| 49 | pid_ = p.Pid(); |
| 50 | } |
| 51 | |
Garrick Evans | 4987953 | 2018-12-03 13:15:36 +0900 | [diff] [blame] | 52 | void HelperProcess::SendMessage( |
| 53 | const google::protobuf::MessageLite& proto) const { |
Taoyu Li | af944c9 | 2019-10-01 12:22:31 +0900 | [diff] [blame] | 54 | msg_dispatcher_->SendMessage(proto); |
| 55 | } |
| 56 | |
| 57 | void HelperProcess::Listen() { |
| 58 | msg_dispatcher_->Start(); |
| 59 | } |
| 60 | |
| 61 | void HelperProcess::RegisterDeviceMessageHandler( |
| 62 | const base::Callback<void(const DeviceMessage&)>& handler) { |
| 63 | msg_dispatcher_->RegisterDeviceMessageHandler(handler); |
Kevin Cernekee | 27bcaa6 | 2016-12-03 11:16:26 -0800 | [diff] [blame] | 64 | } |
| 65 | |
| 66 | } // namespace arc_networkd |