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 | |
| 28 | control_fd_.reset(control[0]); |
| 29 | const int subprocess_fd = control[1]; |
| 30 | |
| 31 | CHECK_GE(argc, 1); |
| 32 | std::vector<std::string> child_argv; |
| 33 | for (int i = 0; i < argc; i++) { |
| 34 | child_argv.push_back(argv[i]); |
| 35 | } |
| 36 | child_argv.push_back(fd_arg + "=" + std::to_string(subprocess_fd)); |
| 37 | |
| 38 | base::FileHandleMappingVector fd_mapping; |
| 39 | fd_mapping.push_back({subprocess_fd, subprocess_fd}); |
| 40 | |
| 41 | base::LaunchOptions options; |
| 42 | options.fds_to_remap = &fd_mapping; |
| 43 | |
| 44 | base::Process p = base::LaunchProcess(child_argv, options); |
| 45 | CHECK(p.IsValid()); |
| 46 | pid_ = p.Pid(); |
| 47 | } |
| 48 | |
Garrick Evans | 4987953 | 2018-12-03 13:15:36 +0900 | [diff] [blame^] | 49 | void HelperProcess::SendMessage( |
| 50 | const google::protobuf::MessageLite& proto) const { |
Kevin Cernekee | 27bcaa6 | 2016-12-03 11:16:26 -0800 | [diff] [blame] | 51 | std::string str; |
| 52 | if (!proto.SerializeToString(&str)) { |
| 53 | LOG(FATAL) << "error serializing protobuf"; |
| 54 | } |
| 55 | if (write(control_fd_.get(), str.data(), str.size()) != |
| 56 | static_cast<ssize_t>(str.size())) { |
| 57 | LOG(FATAL) << "short write on protobuf"; |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | } // namespace arc_networkd |