blob: 238f93c395894856d3fd1f419e20fcf82ba49463 [file] [log] [blame]
Kevin Cernekee27bcaa62016-12-03 11:16:26 -08001// 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 Abe3a7e5132018-02-15 13:07:50 +09005#include "arc/network/helper_process.h"
Kevin Cernekee27bcaa62016-12-03 11:16:26 -08006
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
19namespace arc_networkd {
20
21void 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
49void HelperProcess::SendMessage(const google::protobuf::MessageLite& proto) {
50 std::string str;
51 if (!proto.SerializeToString(&str)) {
52 LOG(FATAL) << "error serializing protobuf";
53 }
54 if (write(control_fd_.get(), str.data(), str.size()) !=
55 static_cast<ssize_t>(str.size())) {
56 LOG(FATAL) << "short write on protobuf";
57 }
58}
59
60} // namespace arc_networkd