blob: 4b4627c33b776771e68249f434cdb41dfd44ee20 [file] [log] [blame]
Kevin Cernekee95d4ae92016-06-19 10:26:29 -07001// 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
Garrick Evans3388a032020-03-24 11:25:55 +09005#include "patchpanel/manager.h"
Kevin Cernekee4e62cc12016-12-03 11:50:53 -08006
Kevin Cernekee95d4ae92016-06-19 10:26:29 -07007#include <arpa/inet.h>
Garrick Evans4ac09852020-01-16 14:09:22 +09008#include <net/if.h>
Hugo Benichi935eca92018-07-03 13:47:24 +09009#include <netinet/in.h>
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070010#include <stdint.h>
Hugo Benichi7352ad92020-04-07 16:11:59 +090011#include <sys/epoll.h>
Garrick Evans54861622019-07-19 09:05:09 +090012#include <sys/prctl.h>
Garrick Evans96e03042019-05-28 14:30:52 +090013#include <sys/socket.h>
14#include <sys/un.h>
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070015
Kevin Cernekee27bcaa62016-12-03 11:16:26 -080016#include <utility>
17
Hugo Benichicc6850f2020-01-17 13:26:06 +090018#include <base/bind.h>
Taoyu Lia0727dc2020-09-24 19:54:59 +090019#include <base/files/scoped_file.h>
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070020#include <base/logging.h>
Qijiang Fan886c4692021-02-19 11:54:10 +090021#include <base/notreached.h>
Taoyu Lic85c44b2019-12-04 17:32:57 +090022#include <base/strings/string_number_conversions.h>
Garrick Evans96e03042019-05-28 14:30:52 +090023#include <base/strings/string_split.h>
Garrick Evans6f258d02019-06-28 16:32:07 +090024#include <base/strings/string_util.h>
Taoyu Li179dcc62019-10-17 11:21:08 +090025#include <base/strings/stringprintf.h>
hschamf9546312020-04-14 15:12:40 +090026#include <base/threading/thread_task_runner_handle.h>
Taoyu Lic85c44b2019-12-04 17:32:57 +090027#include <brillo/key_value_store.h>
Kevin Cernekee27bcaa62016-12-03 11:16:26 -080028#include <brillo/minijail/minijail.h>
29
Garrick Evans3388a032020-03-24 11:25:55 +090030#include "patchpanel/ipc.pb.h"
31#include "patchpanel/mac_address_generator.h"
32#include "patchpanel/net_util.h"
33#include "patchpanel/routing_service.h"
34#include "patchpanel/scoped_ns.h"
Garrick Evans428e4762018-12-11 15:18:42 +090035
Garrick Evans3388a032020-03-24 11:25:55 +090036namespace patchpanel {
Garrick Evans08843932019-09-17 14:41:08 +090037namespace {
Garrick Evans4c042572019-12-17 13:42:25 +090038constexpr int kSubprocessRestartDelayMs = 900;
Garrick Evans08843932019-09-17 14:41:08 +090039
Hugo Benichi7352ad92020-04-07 16:11:59 +090040// Time interval between epoll checks on file descriptors committed by callers
41// of ConnectNamespace DBus API.
42constexpr const base::TimeDelta kConnectNamespaceCheckInterval =
Hugo Benichifa9462e2020-06-26 09:50:48 +090043 base::TimeDelta::FromSeconds(5);
Hugo Benichi7352ad92020-04-07 16:11:59 +090044
Garrick Evans08843932019-09-17 14:41:08 +090045// Passes |method_call| to |handler| and passes the response to
46// |response_sender|. If |handler| returns nullptr, an empty response is
47// created and sent.
48void HandleSynchronousDBusMethodCall(
49 base::Callback<std::unique_ptr<dbus::Response>(dbus::MethodCall*)> handler,
50 dbus::MethodCall* method_call,
51 dbus::ExportedObject::ResponseSender response_sender) {
52 std::unique_ptr<dbus::Response> response = handler.Run(method_call);
53 if (!response)
54 response = dbus::Response::FromMethodCall(method_call);
Qijiang Fan0c657d42020-08-24 19:07:50 +090055 std::move(response_sender).Run(std::move(response));
Garrick Evans08843932019-09-17 14:41:08 +090056}
57
58} // namespace
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070059
Taoyu Lice7caa62019-10-01 15:43:33 +090060Manager::Manager(std::unique_ptr<HelperProcess> adb_proxy,
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090061 std::unique_ptr<HelperProcess> mcast_proxy,
Garrick Evans1f5a3612019-11-08 12:59:03 +090062 std::unique_ptr<HelperProcess> nd_proxy)
Garrick Evans3915af32019-07-25 15:44:34 +090063 : adb_proxy_(std::move(adb_proxy)),
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090064 mcast_proxy_(std::move(mcast_proxy)),
Garrick Evans4ee5ce22020-03-18 07:05:17 +090065 nd_proxy_(std::move(nd_proxy)) {
Taoyu Li179dcc62019-10-17 11:21:08 +090066 runner_ = std::make_unique<MinijailedProcessRunner>();
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090067 datapath_ = std::make_unique<Datapath>(runner_.get(), &firewall_);
Hugo Benichi7352ad92020-04-07 16:11:59 +090068 connected_namespaces_epollfd_ = epoll_create(1 /* size */);
Taoyu Li179dcc62019-10-17 11:21:08 +090069}
Long Chengd4415582019-09-24 19:16:09 +000070
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +090071std::map<const std::string, bool> Manager::cached_feature_enabled_ = {};
72
73bool Manager::ShouldEnableFeature(
74 int min_android_sdk_version,
75 int min_chrome_milestone,
76 const std::vector<std::string>& supported_boards,
77 const std::string& feature_name) {
78 static const char kLsbReleasePath[] = "/etc/lsb-release";
79
80 const auto& cached_result = cached_feature_enabled_.find(feature_name);
81 if (cached_result != cached_feature_enabled_.end())
82 return cached_result->second;
83
84 auto check = [min_android_sdk_version, min_chrome_milestone,
85 &supported_boards, &feature_name]() {
86 brillo::KeyValueStore store;
87 if (!store.Load(base::FilePath(kLsbReleasePath))) {
88 LOG(ERROR) << "Could not read lsb-release";
89 return false;
90 }
91
92 std::string value;
93 if (!store.GetString("CHROMEOS_ARC_ANDROID_SDK_VERSION", &value)) {
94 LOG(ERROR) << feature_name
95 << " disabled - cannot determine Android SDK version";
96 return false;
97 }
98 int ver = 0;
99 if (!base::StringToInt(value.c_str(), &ver)) {
100 LOG(ERROR) << feature_name << " disabled - invalid Android SDK version";
101 return false;
102 }
103 if (ver < min_android_sdk_version) {
104 LOG(INFO) << feature_name << " disabled for Android SDK " << value;
105 return false;
106 }
107
108 if (!store.GetString("CHROMEOS_RELEASE_CHROME_MILESTONE", &value)) {
109 LOG(ERROR) << feature_name
110 << " disabled - cannot determine ChromeOS milestone";
111 return false;
112 }
113 if (!base::StringToInt(value.c_str(), &ver)) {
114 LOG(ERROR) << feature_name << " disabled - invalid ChromeOS milestone";
115 return false;
116 }
117 if (ver < min_chrome_milestone) {
118 LOG(INFO) << feature_name << " disabled for ChromeOS milestone " << value;
119 return false;
120 }
121
122 if (!store.GetString("CHROMEOS_RELEASE_BOARD", &value)) {
123 LOG(ERROR) << feature_name << " disabled - cannot determine board";
124 return false;
125 }
126 if (!supported_boards.empty() &&
127 std::find(supported_boards.begin(), supported_boards.end(), value) ==
128 supported_boards.end()) {
129 LOG(INFO) << feature_name << " disabled for board " << value;
130 return false;
131 }
132 return true;
133 };
134
135 bool result = check();
136 cached_feature_enabled_.emplace(feature_name, result);
137 return result;
138}
139
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700140int Manager::OnInit() {
Garrick Evans54861622019-07-19 09:05:09 +0900141 prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800142
143 // Handle subprocess lifecycle.
144 process_reaper_.Register(this);
Hugo Benichi935eca92018-07-03 13:47:24 +0900145
146 CHECK(process_reaper_.WatchForChild(
Garrick Evans96e03042019-05-28 14:30:52 +0900147 FROM_HERE, adb_proxy_->pid(),
148 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
149 adb_proxy_->pid())))
150 << "Failed to watch adb-proxy child process";
Taoyu Liaf944c92019-10-01 12:22:31 +0900151 CHECK(process_reaper_.WatchForChild(
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900152 FROM_HERE, mcast_proxy_->pid(),
153 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
154 nd_proxy_->pid())))
155 << "Failed to watch multicast-proxy child process";
156 CHECK(process_reaper_.WatchForChild(
Taoyu Liaf944c92019-10-01 12:22:31 +0900157 FROM_HERE, nd_proxy_->pid(),
158 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
159 nd_proxy_->pid())))
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900160 << "Failed to watch nd-proxy child process";
Garrick Evans96e03042019-05-28 14:30:52 +0900161
Garrick Evans49879532018-12-03 13:15:36 +0900162 // Run after Daemon::OnInit().
hschamf9546312020-04-14 15:12:40 +0900163 base::ThreadTaskRunnerHandle::Get()->PostTask(
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700164 FROM_HERE,
165 base::Bind(&Manager::InitialSetup, weak_factory_.GetWeakPtr()));
166
167 return DBusDaemon::OnInit();
168}
169
170void Manager::InitialSetup() {
Garrick Evans08843932019-09-17 14:41:08 +0900171 LOG(INFO) << "Setting up DBus service interface";
172 dbus_svc_path_ = bus_->GetExportedObject(
173 dbus::ObjectPath(patchpanel::kPatchPanelServicePath));
174 if (!dbus_svc_path_) {
175 LOG(FATAL) << "Failed to export " << patchpanel::kPatchPanelServicePath
176 << " object";
177 }
178
Hugo Benichi76be34a2020-08-26 22:35:54 +0900179 shill_client_ = std::make_unique<ShillClient>(bus_);
180
Garrick Evans08843932019-09-17 14:41:08 +0900181 using ServiceMethod =
182 std::unique_ptr<dbus::Response> (Manager::*)(dbus::MethodCall*);
183 const std::map<const char*, ServiceMethod> kServiceMethods = {
184 {patchpanel::kArcStartupMethod, &Manager::OnArcStartup},
185 {patchpanel::kArcShutdownMethod, &Manager::OnArcShutdown},
186 {patchpanel::kArcVmStartupMethod, &Manager::OnArcVmStartup},
187 {patchpanel::kArcVmShutdownMethod, &Manager::OnArcVmShutdown},
Garrick Evans47c19272019-11-21 10:58:21 +0900188 {patchpanel::kTerminaVmStartupMethod, &Manager::OnTerminaVmStartup},
189 {patchpanel::kTerminaVmShutdownMethod, &Manager::OnTerminaVmShutdown},
Garrick Evans51d5b552020-01-30 10:42:06 +0900190 {patchpanel::kPluginVmStartupMethod, &Manager::OnPluginVmStartup},
191 {patchpanel::kPluginVmShutdownMethod, &Manager::OnPluginVmShutdown},
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900192 {patchpanel::kSetVpnIntentMethod, &Manager::OnSetVpnIntent},
Hugo Benichib56b77c2020-01-15 16:00:56 +0900193 {patchpanel::kConnectNamespaceMethod, &Manager::OnConnectNamespace},
Jie Jiang493cde42020-07-17 21:43:39 +0900194 {patchpanel::kGetTrafficCountersMethod, &Manager::OnGetTrafficCounters},
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900195 {patchpanel::kModifyPortRuleMethod, &Manager::OnModifyPortRule},
Garrick Evans02e6e872020-11-30 11:53:13 +0900196 {patchpanel::kGetDevicesMethod, &Manager::OnGetDevices},
Garrick Evans08843932019-09-17 14:41:08 +0900197 };
198
199 for (const auto& kv : kServiceMethods) {
200 if (!dbus_svc_path_->ExportMethodAndBlock(
201 patchpanel::kPatchPanelInterface, kv.first,
202 base::Bind(&HandleSynchronousDBusMethodCall,
203 base::Bind(kv.second, base::Unretained(this))))) {
204 LOG(FATAL) << "Failed to export method " << kv.first;
205 }
206 }
207
208 if (!bus_->RequestOwnershipAndBlock(patchpanel::kPatchPanelServiceName,
209 dbus::Bus::REQUIRE_PRIMARY)) {
210 LOG(FATAL) << "Failed to take ownership of "
211 << patchpanel::kPatchPanelServiceName;
212 }
213 LOG(INFO) << "DBus service interface ready";
214
Hugo Benichifda77232020-08-21 18:28:15 +0900215 routing_svc_ = std::make_unique<RoutingService>();
Hugo Benichi058a26a2020-11-26 10:10:39 +0900216 counters_svc_ =
217 std::make_unique<CountersService>(datapath_.get(), runner_.get());
Hugo Benichifda77232020-08-21 18:28:15 +0900218
Hugo Benichibf811c62020-09-07 17:30:45 +0900219 // b/162966185: Allow Jetstream to disable:
220 // - the IP forwarding setup used for hosting VMs and containers,
221 // - the iptables rules for fwmark based routing.
222 if (!USE_JETSTREAM_ROUTING) {
223 datapath_->Start();
Hugo Benichi2a940542020-10-26 18:50:49 +0900224 shill_client_->RegisterDefaultDeviceChangedHandler(base::BindRepeating(
225 &Manager::OnDefaultDeviceChanged, weak_factory_.GetWeakPtr()));
Hugo Benichibf811c62020-09-07 17:30:45 +0900226 shill_client_->RegisterDevicesChangedHandler(base::BindRepeating(
227 &Manager::OnDevicesChanged, weak_factory_.GetWeakPtr()));
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900228 shill_client_->RegisterIPConfigsChangedHandler(base::BindRepeating(
229 &Manager::OnIPConfigsChanged, weak_factory_.GetWeakPtr()));
Hugo Benichibf811c62020-09-07 17:30:45 +0900230 }
Hugo Benichifda77232020-08-21 18:28:15 +0900231
Taoyu Lia0727dc2020-09-24 19:54:59 +0900232 nd_proxy_->RegisterNDProxyMessageHandler(
233 base::Bind(&Manager::OnNDProxyMessage, weak_factory_.GetWeakPtr()));
Hugo Benichifda77232020-08-21 18:28:15 +0900234
Hugo Benichifda77232020-08-21 18:28:15 +0900235 auto* const forwarder = static_cast<TrafficForwarder*>(this);
236
237 GuestMessage::GuestType arc_guest =
238 USE_ARCVM ? GuestMessage::ARC_VM : GuestMessage::ARC;
Garrick Evans209a80a2020-11-30 14:42:40 +0900239 arc_svc_ = std::make_unique<ArcService>(
240 shill_client_.get(), datapath_.get(), &addr_mgr_, forwarder, arc_guest,
241 base::BindRepeating(&Manager::OnDeviceChanged,
242 weak_factory_.GetWeakPtr()));
243 cros_svc_ = std::make_unique<CrostiniService>(
244 shill_client_.get(), &addr_mgr_, datapath_.get(), forwarder,
245 base::BindRepeating(&Manager::OnDeviceChanged,
246 weak_factory_.GetWeakPtr()));
Jie Jiang84966852020-09-18 18:49:05 +0900247 network_monitor_svc_ = std::make_unique<NetworkMonitorService>(
248 shill_client_.get(),
Jie Jiang25c1b972020-11-12 15:42:53 +0900249 base::BindRepeating(&Manager::OnNeighborReachabilityEvent,
Jie Jiang84966852020-09-18 18:49:05 +0900250 weak_factory_.GetWeakPtr()));
Hugo Benichifda77232020-08-21 18:28:15 +0900251 network_monitor_svc_->Start();
Hugo Benichi058a26a2020-11-26 10:10:39 +0900252 counters_svc_->Init(shill_client_->get_devices());
Hugo Benichifda77232020-08-21 18:28:15 +0900253 nd_proxy_->Listen();
254}
255
256void Manager::OnShutdown(int* exit_code) {
257 LOG(INFO) << "Shutting down and cleaning up";
Jie Jiang84966852020-09-18 18:49:05 +0900258 network_monitor_svc_.reset();
Hugo Benichifda77232020-08-21 18:28:15 +0900259 cros_svc_.reset();
260 arc_svc_.reset();
261 close(connected_namespaces_epollfd_);
262 // Tear down any remaining connected namespace.
263 std::vector<int> connected_namespaces_fdkeys;
264 for (const auto& kv : connected_namespaces_)
265 connected_namespaces_fdkeys.push_back(kv.first);
266 for (const int fdkey : connected_namespaces_fdkeys)
267 DisconnectNamespace(fdkey);
Hugo Benichibf811c62020-09-07 17:30:45 +0900268 if (!USE_JETSTREAM_ROUTING)
269 datapath_->Stop();
Jie Jiang00592cf2020-12-17 11:23:49 +0900270
271 brillo::DBusDaemon::OnShutdown(exit_code);
Hugo Benichifda77232020-08-21 18:28:15 +0900272}
273
274void Manager::OnSubprocessExited(pid_t pid, const siginfo_t&) {
275 LOG(ERROR) << "Subprocess " << pid << " exited unexpectedly -"
276 << " attempting to restart";
277
278 HelperProcess* proc;
279 if (pid == adb_proxy_->pid()) {
280 proc = adb_proxy_.get();
281 } else if (pid == mcast_proxy_->pid()) {
282 proc = mcast_proxy_.get();
283 } else if (pid == nd_proxy_->pid()) {
284 proc = nd_proxy_.get();
285 } else {
286 LOG(DFATAL) << "Unknown child process";
287 return;
288 }
289
290 process_reaper_.ForgetChild(pid);
291
292 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
293 FROM_HERE,
294 base::Bind(&Manager::RestartSubprocess, weak_factory_.GetWeakPtr(), proc),
295 base::TimeDelta::FromMilliseconds((2 << proc->restarts()) *
296 kSubprocessRestartDelayMs));
297}
298
299void Manager::RestartSubprocess(HelperProcess* subproc) {
300 if (subproc->Restart()) {
301 DCHECK(process_reaper_.WatchForChild(
302 FROM_HERE, subproc->pid(),
303 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
304 subproc->pid())))
305 << "Failed to watch child process " << subproc->pid();
306 }
307}
308
Hugo Benichi2a940542020-10-26 18:50:49 +0900309void Manager::OnDefaultDeviceChanged(const ShillClient::Device& new_device,
310 const ShillClient::Device& prev_device) {
311 // Only take into account interface switches and ignore layer 3 property
312 // changes.
313 if (prev_device.ifname == new_device.ifname)
314 return;
315
Hugo Benichi058a26a2020-11-26 10:10:39 +0900316 if (prev_device.type == ShillClient::Device::Type::kVPN) {
Hugo Benichi2a940542020-10-26 18:50:49 +0900317 datapath_->StopVpnRouting(prev_device.ifname);
Hugo Benichi058a26a2020-11-26 10:10:39 +0900318 counters_svc_->OnVpnDeviceRemoved(prev_device.ifname);
319 }
Hugo Benichi2a940542020-10-26 18:50:49 +0900320
Hugo Benichi058a26a2020-11-26 10:10:39 +0900321 if (new_device.type == ShillClient::Device::Type::kVPN) {
Hugo Benichi2a940542020-10-26 18:50:49 +0900322 datapath_->StartVpnRouting(new_device.ifname);
Hugo Benichi058a26a2020-11-26 10:10:39 +0900323 counters_svc_->OnVpnDeviceAdded(new_device.ifname);
324 }
Hugo Benichi2a940542020-10-26 18:50:49 +0900325}
326
Hugo Benichi76be34a2020-08-26 22:35:54 +0900327void Manager::OnDevicesChanged(const std::set<std::string>& added,
328 const std::set<std::string>& removed) {
Hugo Benichi058a26a2020-11-26 10:10:39 +0900329 for (const std::string& ifname : removed) {
Hugo Benichi76be34a2020-08-26 22:35:54 +0900330 datapath_->StopConnectionPinning(ifname);
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900331 datapath_->RemoveRedirectDnsRule(ifname);
Hugo Benichi058a26a2020-11-26 10:10:39 +0900332 counters_svc_->OnPhysicalDeviceRemoved(ifname);
333 }
Hugo Benichi76be34a2020-08-26 22:35:54 +0900334
Hugo Benichi058a26a2020-11-26 10:10:39 +0900335 for (const std::string& ifname : added) {
Hugo Benichi76be34a2020-08-26 22:35:54 +0900336 datapath_->StartConnectionPinning(ifname);
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900337 ShillClient::Device device;
338 if (!shill_client_->GetDeviceProperties(ifname, &device))
339 continue;
340
341 if (!device.ipconfig.ipv4_dns_addresses.empty())
342 datapath_->AddRedirectDnsRule(ifname,
343 device.ipconfig.ipv4_dns_addresses.front());
344
Hugo Benichi058a26a2020-11-26 10:10:39 +0900345 counters_svc_->OnPhysicalDeviceAdded(ifname);
346 }
Hugo Benichi76be34a2020-08-26 22:35:54 +0900347}
348
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900349void Manager::OnIPConfigsChanged(const std::string& device,
350 const ShillClient::IPConfig& ipconfig) {
351 if (ipconfig.ipv4_dns_addresses.empty()) {
352 datapath_->RemoveRedirectDnsRule(device);
353 } else {
354 datapath_->AddRedirectDnsRule(device, ipconfig.ipv4_dns_addresses.front());
355 }
356}
357
Garrick Evans209a80a2020-11-30 14:42:40 +0900358void Manager::OnDeviceChanged(const Device& device,
359 Device::ChangeEvent event,
360 GuestMessage::GuestType guest_type) {
361 dbus::Signal signal(kPatchPanelInterface, kNetworkDeviceChangedSignal);
362 NetworkDeviceChangedSignal proto;
363 proto.set_event(event == Device::ChangeEvent::ADDED
364 ? NetworkDeviceChangedSignal::DEVICE_ADDED
365 : NetworkDeviceChangedSignal::DEVICE_REMOVED);
366 auto* dev = proto.mutable_device();
367 dev->set_ifname(device.host_ifname());
Garrick Evans9ccd2a62021-02-18 14:48:28 +0900368 dev->set_phys_ifname(device.phys_ifname());
Garrick Evans209a80a2020-11-30 14:42:40 +0900369 dev->set_ipv4_addr(device.config().guest_ipv4_addr());
370 if (const auto* subnet = device.config().ipv4_subnet()) {
371 auto* sub = dev->mutable_ipv4_subnet();
372 sub->set_base_addr(subnet->BaseAddress());
373 sub->set_prefix_len(subnet->PrefixLength());
374 }
375 switch (guest_type) {
376 case GuestMessage::ARC:
377 dev->set_guest_type(NetworkDevice::ARC);
378 break;
379 case GuestMessage::ARC_VM:
380 dev->set_guest_type(NetworkDevice::ARCVM);
381 break;
382 case GuestMessage::TERMINA_VM:
383 dev->set_guest_type(NetworkDevice::TERMINA_VM);
384 break;
385 case GuestMessage::PLUGIN_VM:
386 dev->set_guest_type(NetworkDevice::PLUGIN_VM);
387 break;
388 default:
389 LOG(ERROR) << "Unknown device type";
390 }
391
392 dbus::MessageWriter(&signal).AppendProtoAsArrayOfBytes(proto);
393 dbus_svc_path_->SendSignal(&signal);
394}
395
Garrick Evanse94a14e2019-11-11 10:32:13 +0900396bool Manager::StartArc(pid_t pid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900397 if (!arc_svc_->Start(pid))
398 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900399
400 GuestMessage msg;
401 msg.set_event(GuestMessage::START);
402 msg.set_type(GuestMessage::ARC);
403 msg.set_arc_pid(pid);
404 SendGuestMessage(msg);
405
406 return true;
407}
408
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900409void Manager::StopArc() {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900410 GuestMessage msg;
411 msg.set_event(GuestMessage::STOP);
412 msg.set_type(GuestMessage::ARC);
413 SendGuestMessage(msg);
414
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900415 // After the ARC container has stopped, the pid is not known anymore.
416 // The pid argument is ignored by ArcService.
417 arc_svc_->Stop(0);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900418}
419
Garrick Evans015b0d62020-02-07 09:06:38 +0900420bool Manager::StartArcVm(uint32_t cid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900421 if (!arc_svc_->Start(cid))
422 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900423
424 GuestMessage msg;
425 msg.set_event(GuestMessage::START);
426 msg.set_type(GuestMessage::ARC_VM);
427 msg.set_arcvm_vsock_cid(cid);
428 SendGuestMessage(msg);
429
430 return true;
431}
432
Garrick Evans015b0d62020-02-07 09:06:38 +0900433void Manager::StopArcVm(uint32_t cid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900434 GuestMessage msg;
435 msg.set_event(GuestMessage::STOP);
436 msg.set_type(GuestMessage::ARC_VM);
437 SendGuestMessage(msg);
438
Garrick Evans21173b12019-11-20 15:23:16 +0900439 arc_svc_->Stop(cid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900440}
441
Garrick Evans51d5b552020-01-30 10:42:06 +0900442bool Manager::StartCrosVm(uint64_t vm_id,
443 GuestMessage::GuestType vm_type,
Garrick Evans53a2a982020-02-05 10:53:35 +0900444 uint32_t subnet_index) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900445 DCHECK(vm_type == GuestMessage::TERMINA_VM ||
446 vm_type == GuestMessage::PLUGIN_VM);
447
448 if (!cros_svc_->Start(vm_id, vm_type == GuestMessage::TERMINA_VM,
449 subnet_index))
Garrick Evans47c19272019-11-21 10:58:21 +0900450 return false;
451
452 GuestMessage msg;
453 msg.set_event(GuestMessage::START);
Garrick Evans51d5b552020-01-30 10:42:06 +0900454 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900455 SendGuestMessage(msg);
456
457 return true;
458}
459
Garrick Evans51d5b552020-01-30 10:42:06 +0900460void Manager::StopCrosVm(uint64_t vm_id, GuestMessage::GuestType vm_type) {
Garrick Evans47c19272019-11-21 10:58:21 +0900461 GuestMessage msg;
462 msg.set_event(GuestMessage::STOP);
Garrick Evans51d5b552020-01-30 10:42:06 +0900463 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900464 SendGuestMessage(msg);
465
Garrick Evans51d5b552020-01-30 10:42:06 +0900466 cros_svc_->Stop(vm_id, vm_type == GuestMessage::TERMINA_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900467}
468
Garrick Evans02e6e872020-11-30 11:53:13 +0900469std::unique_ptr<dbus::Response> Manager::OnGetDevices(
470 dbus::MethodCall* method_call) {
471 std::unique_ptr<dbus::Response> dbus_response(
472 dbus::Response::FromMethodCall(method_call));
473
474 dbus::MessageReader reader(method_call);
475 dbus::MessageWriter writer(dbus_response.get());
476
477 patchpanel::GetDevicesRequest request;
478 patchpanel::GetDevicesResponse response;
479
480 if (!reader.PopArrayOfBytesAsProto(&request)) {
481 LOG(ERROR) << "Unable to parse request";
482 writer.AppendProtoAsArrayOfBytes(response);
483 return dbus_response;
484 }
485
486 static const auto arc_guest_type =
487 USE_ARCVM ? NetworkDevice::ARCVM : NetworkDevice::ARC;
488
489 arc_svc_->ScanDevices(base::BindRepeating(
490 [](patchpanel::GetDevicesResponse* resp, const Device& device) {
491 auto* dev = resp->add_devices();
492 dev->set_ifname(device.host_ifname());
Garrick Evans9ccd2a62021-02-18 14:48:28 +0900493 dev->set_phys_ifname(device.phys_ifname());
Garrick Evans02e6e872020-11-30 11:53:13 +0900494 dev->set_ipv4_addr(device.config().guest_ipv4_addr());
495 dev->set_guest_type(arc_guest_type);
496 if (const auto* subnet = device.config().ipv4_subnet()) {
497 auto* sub = dev->mutable_ipv4_subnet();
498 sub->set_base_addr(subnet->BaseAddress());
499 sub->set_prefix_len(subnet->PrefixLength());
500 }
501 },
502 &response));
503
504 cros_svc_->ScanDevices(base::BindRepeating(
505 [](patchpanel::GetDevicesResponse* resp, uint64_t vm_id, bool is_termina,
506 const Device& device) {
507 auto* dev = resp->add_devices();
508 dev->set_ifname(device.host_ifname());
Garrick Evans9ccd2a62021-02-18 14:48:28 +0900509 dev->set_phys_ifname(device.phys_ifname());
Garrick Evans02e6e872020-11-30 11:53:13 +0900510 dev->set_ipv4_addr(device.config().guest_ipv4_addr());
511 dev->set_guest_type(is_termina ? NetworkDevice::TERMINA_VM
512 : NetworkDevice::PLUGIN_VM);
513 if (const auto* subnet = device.config().ipv4_subnet()) {
514 auto* sub = dev->mutable_ipv4_subnet();
515 sub->set_base_addr(subnet->BaseAddress());
516 sub->set_prefix_len(subnet->PrefixLength());
517 }
518 },
519 &response));
520
521 writer.AppendProtoAsArrayOfBytes(response);
522 return dbus_response;
523}
524
Garrick Evans08843932019-09-17 14:41:08 +0900525std::unique_ptr<dbus::Response> Manager::OnArcStartup(
526 dbus::MethodCall* method_call) {
527 LOG(INFO) << "ARC++ starting up";
528
529 std::unique_ptr<dbus::Response> dbus_response(
530 dbus::Response::FromMethodCall(method_call));
531
532 dbus::MessageReader reader(method_call);
533 dbus::MessageWriter writer(dbus_response.get());
534
535 patchpanel::ArcStartupRequest request;
536 patchpanel::ArcStartupResponse response;
537
538 if (!reader.PopArrayOfBytesAsProto(&request)) {
539 LOG(ERROR) << "Unable to parse request";
540 writer.AppendProtoAsArrayOfBytes(response);
541 return dbus_response;
542 }
543
Garrick Evanse01bf072019-11-15 09:08:19 +0900544 if (!StartArc(request.pid()))
545 LOG(ERROR) << "Failed to start ARC++ network service";
Garrick Evanse94a14e2019-11-11 10:32:13 +0900546
Garrick Evans08843932019-09-17 14:41:08 +0900547 writer.AppendProtoAsArrayOfBytes(response);
548 return dbus_response;
549}
550
551std::unique_ptr<dbus::Response> Manager::OnArcShutdown(
552 dbus::MethodCall* method_call) {
553 LOG(INFO) << "ARC++ shutting down";
554
555 std::unique_ptr<dbus::Response> dbus_response(
556 dbus::Response::FromMethodCall(method_call));
557
558 dbus::MessageReader reader(method_call);
559 dbus::MessageWriter writer(dbus_response.get());
560
561 patchpanel::ArcShutdownRequest request;
562 patchpanel::ArcShutdownResponse response;
563
564 if (!reader.PopArrayOfBytesAsProto(&request)) {
565 LOG(ERROR) << "Unable to parse request";
566 writer.AppendProtoAsArrayOfBytes(response);
567 return dbus_response;
568 }
569
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900570 StopArc();
Garrick Evanse94a14e2019-11-11 10:32:13 +0900571
Garrick Evans08843932019-09-17 14:41:08 +0900572 writer.AppendProtoAsArrayOfBytes(response);
573 return dbus_response;
574}
575
576std::unique_ptr<dbus::Response> Manager::OnArcVmStartup(
577 dbus::MethodCall* method_call) {
578 LOG(INFO) << "ARCVM starting up";
579
580 std::unique_ptr<dbus::Response> dbus_response(
581 dbus::Response::FromMethodCall(method_call));
582
583 dbus::MessageReader reader(method_call);
584 dbus::MessageWriter writer(dbus_response.get());
585
586 patchpanel::ArcVmStartupRequest request;
587 patchpanel::ArcVmStartupResponse response;
588
589 if (!reader.PopArrayOfBytesAsProto(&request)) {
590 LOG(ERROR) << "Unable to parse request";
591 writer.AppendProtoAsArrayOfBytes(response);
592 return dbus_response;
593 }
594
Garrick Evans47c19272019-11-21 10:58:21 +0900595 if (!StartArcVm(request.cid())) {
Garrick Evanse01bf072019-11-15 09:08:19 +0900596 LOG(ERROR) << "Failed to start ARCVM network service";
Garrick Evans47c19272019-11-21 10:58:21 +0900597 writer.AppendProtoAsArrayOfBytes(response);
598 return dbus_response;
Garrick Evanse01bf072019-11-15 09:08:19 +0900599 }
Garrick Evanse94a14e2019-11-11 10:32:13 +0900600
Garrick Evans47c19272019-11-21 10:58:21 +0900601 // Populate the response with the known devices.
Garrick Evans38b25a42020-04-06 15:17:42 +0900602 for (const auto* config : arc_svc_->GetDeviceConfigs()) {
603 if (config->tap_ifname().empty())
604 continue;
Garrick Evans47c19272019-11-21 10:58:21 +0900605
Garrick Evans38b25a42020-04-06 15:17:42 +0900606 auto* dev = response.add_devices();
607 dev->set_ifname(config->tap_ifname());
608 dev->set_ipv4_addr(config->guest_ipv4_addr());
Garrick Evansa0c9c972020-11-30 09:54:59 +0900609 dev->set_guest_type(NetworkDevice::ARCVM);
Garrick Evans38b25a42020-04-06 15:17:42 +0900610 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900611
Garrick Evans08843932019-09-17 14:41:08 +0900612 writer.AppendProtoAsArrayOfBytes(response);
613 return dbus_response;
614}
615
616std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
617 dbus::MethodCall* method_call) {
618 LOG(INFO) << "ARCVM shutting down";
619
620 std::unique_ptr<dbus::Response> dbus_response(
621 dbus::Response::FromMethodCall(method_call));
622
623 dbus::MessageReader reader(method_call);
624 dbus::MessageWriter writer(dbus_response.get());
625
626 patchpanel::ArcVmShutdownRequest request;
627 patchpanel::ArcVmShutdownResponse response;
628
629 if (!reader.PopArrayOfBytesAsProto(&request)) {
630 LOG(ERROR) << "Unable to parse request";
631 writer.AppendProtoAsArrayOfBytes(response);
632 return dbus_response;
633 }
634
Garrick Evans21173b12019-11-20 15:23:16 +0900635 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900636
Garrick Evans08843932019-09-17 14:41:08 +0900637 writer.AppendProtoAsArrayOfBytes(response);
638 return dbus_response;
639}
640
Garrick Evans47c19272019-11-21 10:58:21 +0900641std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
642 dbus::MethodCall* method_call) {
643 LOG(INFO) << "Termina VM starting up";
644
645 std::unique_ptr<dbus::Response> dbus_response(
646 dbus::Response::FromMethodCall(method_call));
647
648 dbus::MessageReader reader(method_call);
649 dbus::MessageWriter writer(dbus_response.get());
650
651 patchpanel::TerminaVmStartupRequest request;
652 patchpanel::TerminaVmStartupResponse response;
653
654 if (!reader.PopArrayOfBytesAsProto(&request)) {
655 LOG(ERROR) << "Unable to parse request";
656 writer.AppendProtoAsArrayOfBytes(response);
657 return dbus_response;
658 }
659
660 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900661 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900662 LOG(ERROR) << "Failed to start Termina VM network service";
663 writer.AppendProtoAsArrayOfBytes(response);
664 return dbus_response;
665 }
666
Garrick Evans51d5b552020-01-30 10:42:06 +0900667 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900668 if (!tap) {
669 LOG(DFATAL) << "TAP device missing";
670 writer.AppendProtoAsArrayOfBytes(response);
671 return dbus_response;
672 }
Garrick Evans47c19272019-11-21 10:58:21 +0900673
Garrick Evansb1c93712020-01-22 09:28:25 +0900674 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900675 dev->set_ifname(tap->host_ifname());
Garrick Evansa0c9c972020-11-30 09:54:59 +0900676 dev->set_guest_type(NetworkDevice::TERMINA_VM);
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900677 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900678 if (!subnet) {
679 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
680 writer.AppendProtoAsArrayOfBytes(response);
681 return dbus_response;
682 }
683 auto* resp_subnet = dev->mutable_ipv4_subnet();
684 resp_subnet->set_base_addr(subnet->BaseAddress());
685 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900686 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900687 if (!subnet) {
688 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
689 writer.AppendProtoAsArrayOfBytes(response);
690 return dbus_response;
691 }
692 resp_subnet = response.mutable_container_subnet();
693 resp_subnet->set_base_addr(subnet->BaseAddress());
694 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900695
696 writer.AppendProtoAsArrayOfBytes(response);
697 return dbus_response;
698}
699
700std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
701 dbus::MethodCall* method_call) {
702 LOG(INFO) << "Termina VM shutting down";
703
704 std::unique_ptr<dbus::Response> dbus_response(
705 dbus::Response::FromMethodCall(method_call));
706
707 dbus::MessageReader reader(method_call);
708 dbus::MessageWriter writer(dbus_response.get());
709
710 patchpanel::TerminaVmShutdownRequest request;
711 patchpanel::TerminaVmShutdownResponse response;
712
713 if (!reader.PopArrayOfBytesAsProto(&request)) {
714 LOG(ERROR) << "Unable to parse request";
715 writer.AppendProtoAsArrayOfBytes(response);
716 return dbus_response;
717 }
718
Garrick Evans51d5b552020-01-30 10:42:06 +0900719 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
720
721 writer.AppendProtoAsArrayOfBytes(response);
722 return dbus_response;
723}
724
725std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
726 dbus::MethodCall* method_call) {
727 LOG(INFO) << "Plugin VM starting up";
728
729 std::unique_ptr<dbus::Response> dbus_response(
730 dbus::Response::FromMethodCall(method_call));
731
732 dbus::MessageReader reader(method_call);
733 dbus::MessageWriter writer(dbus_response.get());
734
735 patchpanel::PluginVmStartupRequest request;
736 patchpanel::PluginVmStartupResponse response;
737
738 if (!reader.PopArrayOfBytesAsProto(&request)) {
739 LOG(ERROR) << "Unable to parse request";
740 writer.AppendProtoAsArrayOfBytes(response);
741 return dbus_response;
742 }
743
Garrick Evans08fb34b2020-02-20 10:50:17 +0900744 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900745 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900746 LOG(ERROR) << "Failed to start Plugin VM network service";
747 writer.AppendProtoAsArrayOfBytes(response);
748 return dbus_response;
749 }
750
751 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
752 if (!tap) {
753 LOG(DFATAL) << "TAP device missing";
754 writer.AppendProtoAsArrayOfBytes(response);
755 return dbus_response;
756 }
757
Garrick Evans51d5b552020-01-30 10:42:06 +0900758 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900759 dev->set_ifname(tap->host_ifname());
Garrick Evansa0c9c972020-11-30 09:54:59 +0900760 dev->set_guest_type(NetworkDevice::PLUGIN_VM);
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900761 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900762 if (!subnet) {
763 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
764 writer.AppendProtoAsArrayOfBytes(response);
765 return dbus_response;
766 }
767 auto* resp_subnet = dev->mutable_ipv4_subnet();
768 resp_subnet->set_base_addr(subnet->BaseAddress());
769 resp_subnet->set_prefix_len(subnet->PrefixLength());
770
771 writer.AppendProtoAsArrayOfBytes(response);
772 return dbus_response;
773}
774
775std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
776 dbus::MethodCall* method_call) {
777 LOG(INFO) << "Plugin VM shutting down";
778
779 std::unique_ptr<dbus::Response> dbus_response(
780 dbus::Response::FromMethodCall(method_call));
781
782 dbus::MessageReader reader(method_call);
783 dbus::MessageWriter writer(dbus_response.get());
784
785 patchpanel::PluginVmShutdownRequest request;
786 patchpanel::PluginVmShutdownResponse response;
787
788 if (!reader.PopArrayOfBytesAsProto(&request)) {
789 LOG(ERROR) << "Unable to parse request";
790 writer.AppendProtoAsArrayOfBytes(response);
791 return dbus_response;
792 }
793
794 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900795
796 writer.AppendProtoAsArrayOfBytes(response);
797 return dbus_response;
798}
799
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900800std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
801 dbus::MethodCall* method_call) {
802 std::unique_ptr<dbus::Response> dbus_response(
803 dbus::Response::FromMethodCall(method_call));
804
805 dbus::MessageReader reader(method_call);
806 dbus::MessageWriter writer(dbus_response.get());
807
808 patchpanel::SetVpnIntentRequest request;
809 patchpanel::SetVpnIntentResponse response;
810
811 bool success = reader.PopArrayOfBytesAsProto(&request);
812 if (!success) {
813 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
814 // Do not return yet to make sure we close the received fd.
815 }
816
817 base::ScopedFD client_socket;
818 reader.PopFileDescriptor(&client_socket);
819
820 if (success)
821 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
822
823 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900824
825 writer.AppendProtoAsArrayOfBytes(response);
826 return dbus_response;
827}
828
829std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
830 dbus::MethodCall* method_call) {
831 std::unique_ptr<dbus::Response> dbus_response(
832 dbus::Response::FromMethodCall(method_call));
833
834 dbus::MessageReader reader(method_call);
835 dbus::MessageWriter writer(dbus_response.get());
836
837 patchpanel::ConnectNamespaceRequest request;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900838
839 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900840 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
841 // Do not return yet to make sure we close the received fd and
842 // validate other arguments.
Hugo Benichi7c342672020-09-08 09:18:14 +0900843 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
844 return dbus_response;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900845 }
846
Hugo Benichicc6850f2020-01-17 13:26:06 +0900847 base::ScopedFD client_fd;
848 reader.PopFileDescriptor(&client_fd);
849 if (!client_fd.is_valid()) {
850 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
Hugo Benichi7c342672020-09-08 09:18:14 +0900851 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
852 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900853 }
854
855 pid_t pid = request.pid();
Garrick Evans263bd952020-12-03 20:27:43 +0900856 if (pid == 1 || pid == getpid()) {
857 LOG(ERROR) << "ConnectNamespaceRequest: privileged namespace pid " << pid;
858 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
859 return dbus_response;
860 }
Hugo Benichicc6850f2020-01-17 13:26:06 +0900861 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900862 ScopedNS ns(pid, ScopedNS::Type::Network);
Hugo Benichicc6850f2020-01-17 13:26:06 +0900863 if (!ns.IsValid()) {
864 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900865 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
866 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900867 }
868 }
869
870 const std::string& outbound_ifname = request.outbound_physical_device();
871 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
872 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
873 << outbound_ifname;
Hugo Benichi7c342672020-09-08 09:18:14 +0900874 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
875 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900876 }
877
Hugo Benichi7c342672020-09-08 09:18:14 +0900878 auto response = ConnectNamespace(std::move(client_fd), request);
879 writer.AppendProtoAsArrayOfBytes(*response);
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900880 return dbus_response;
881}
882
Jie Jiang493cde42020-07-17 21:43:39 +0900883std::unique_ptr<dbus::Response> Manager::OnGetTrafficCounters(
884 dbus::MethodCall* method_call) {
885 std::unique_ptr<dbus::Response> dbus_response(
886 dbus::Response::FromMethodCall(method_call));
887
888 dbus::MessageReader reader(method_call);
889 dbus::MessageWriter writer(dbus_response.get());
890
891 patchpanel::TrafficCountersRequest request;
892 patchpanel::TrafficCountersResponse response;
893
894 if (!reader.PopArrayOfBytesAsProto(&request)) {
895 LOG(ERROR) << "Unable to parse TrafficCountersRequest";
896 writer.AppendProtoAsArrayOfBytes(response);
897 return dbus_response;
898 }
899
900 const std::set<std::string> devices{request.devices().begin(),
901 request.devices().end()};
902 const auto counters = counters_svc_->GetCounters(devices);
903 for (const auto& kv : counters) {
904 auto* traffic_counter = response.add_counters();
905 const auto& source_and_device = kv.first;
906 const auto& counter = kv.second;
907 traffic_counter->set_source(source_and_device.first);
908 traffic_counter->set_device(source_and_device.second);
909 traffic_counter->set_rx_bytes(counter.rx_bytes);
910 traffic_counter->set_rx_packets(counter.rx_packets);
911 traffic_counter->set_tx_bytes(counter.tx_bytes);
912 traffic_counter->set_tx_packets(counter.tx_packets);
913 }
914
915 writer.AppendProtoAsArrayOfBytes(response);
916 return dbus_response;
917}
918
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900919std::unique_ptr<dbus::Response> Manager::OnModifyPortRule(
920 dbus::MethodCall* method_call) {
921 std::unique_ptr<dbus::Response> dbus_response(
922 dbus::Response::FromMethodCall(method_call));
923
924 dbus::MessageReader reader(method_call);
925 dbus::MessageWriter writer(dbus_response.get());
926
927 patchpanel::ModifyPortRuleRequest request;
928 patchpanel::ModifyPortRuleResponse response;
929
930 if (!reader.PopArrayOfBytesAsProto(&request)) {
931 LOG(ERROR) << "Unable to parse ModifyPortRequest";
932 writer.AppendProtoAsArrayOfBytes(response);
933 return dbus_response;
934 }
935
Jason Jeremy Imanc28df852020-07-11 17:38:26 +0900936 response.set_success(ModifyPortRule(request));
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900937 writer.AppendProtoAsArrayOfBytes(response);
938 return dbus_response;
939}
940
Jie Jiang25c1b972020-11-12 15:42:53 +0900941void Manager::OnNeighborReachabilityEvent(
Jie Jiang84966852020-09-18 18:49:05 +0900942 int ifindex,
943 const shill::IPAddress& ip_addr,
944 NeighborLinkMonitor::NeighborRole role,
Jie Jiang25c1b972020-11-12 15:42:53 +0900945 NeighborReachabilityEventSignal::EventType event_type) {
Jie Jiang84966852020-09-18 18:49:05 +0900946 if (!ip_addr.IsValid()) {
947 LOG(DFATAL) << "ip_addr is not valid";
948 return;
949 }
950
Jie Jiang25c1b972020-11-12 15:42:53 +0900951 using SignalProto = NeighborReachabilityEventSignal;
Jie Jiang84966852020-09-18 18:49:05 +0900952 SignalProto proto;
953 proto.set_ifindex(ifindex);
954 proto.set_ip_addr(ip_addr.ToString());
Jie Jiang25c1b972020-11-12 15:42:53 +0900955 proto.set_type(event_type);
Jie Jiang84966852020-09-18 18:49:05 +0900956 switch (role) {
957 case NeighborLinkMonitor::NeighborRole::kGateway:
958 proto.set_role(SignalProto::GATEWAY);
959 break;
960 case NeighborLinkMonitor::NeighborRole::kDNSServer:
961 proto.set_role(SignalProto::DNS_SERVER);
962 break;
963 case NeighborLinkMonitor::NeighborRole::kGatewayAndDNSServer:
964 proto.set_role(SignalProto::GATEWAY_AND_DNS_SERVER);
965 break;
966 default:
967 NOTREACHED();
968 }
969
Jie Jiang25c1b972020-11-12 15:42:53 +0900970 dbus::Signal signal(kPatchPanelInterface, kNeighborReachabilityEventSignal);
Jie Jiang84966852020-09-18 18:49:05 +0900971 dbus::MessageWriter writer(&signal);
972 if (!writer.AppendProtoAsArrayOfBytes(proto)) {
Jie Jiang25c1b972020-11-12 15:42:53 +0900973 LOG(ERROR) << "Failed to encode proto NeighborReachabilityEventSignal";
Jie Jiang84966852020-09-18 18:49:05 +0900974 return;
975 }
976
977 dbus_svc_path_->SendSignal(&signal);
978}
979
Hugo Benichi7c342672020-09-08 09:18:14 +0900980std::unique_ptr<patchpanel::ConnectNamespaceResponse> Manager::ConnectNamespace(
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900981 base::ScopedFD client_fd,
Hugo Benichi7c342672020-09-08 09:18:14 +0900982 const patchpanel::ConnectNamespaceRequest& request) {
983 auto response = std::make_unique<patchpanel::ConnectNamespaceResponse>();
984
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900985 std::unique_ptr<Subnet> subnet =
986 addr_mgr_.AllocateIPv4Subnet(AddressManager::Guest::MINIJAIL_NETNS);
987 if (!subnet) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900988 LOG(ERROR) << "ConnectNamespace: exhausted IPv4 subnet space";
989 return response;
Hugo Benichie8758b52020-04-03 14:49:01 +0900990 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900991
Hugo Benichi7352ad92020-04-07 16:11:59 +0900992 // Dup the client fd into our own: this guarantees that the fd number will
993 // be stable and tied to the actual kernel resources used by the client.
994 base::ScopedFD local_client_fd(dup(client_fd.get()));
995 if (!local_client_fd.is_valid()) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900996 PLOG(ERROR) << "ConnectNamespace: failed to dup() client fd";
997 return response;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900998 }
999
Hugo Benichi7c342672020-09-08 09:18:14 +09001000 // Add the duped fd to the epoll watcher.
Hugo Benichi7352ad92020-04-07 16:11:59 +09001001 // TODO(hugobenichi) Find a way to reuse base::FileDescriptorWatcher for
1002 // listening to EPOLLHUP.
1003 struct epoll_event epevent;
1004 epevent.events = EPOLLIN; // EPOLLERR | EPOLLHUP are always waited for.
1005 epevent.data.fd = local_client_fd.get();
1006 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_ADD,
1007 local_client_fd.get(), &epevent) != 0) {
Hugo Benichi7c342672020-09-08 09:18:14 +09001008 PLOG(ERROR) << "ConnectNamespace: epoll_ctl(EPOLL_CTL_ADD) failed";
1009 return response;
Hugo Benichi7352ad92020-04-07 16:11:59 +09001010 }
1011
Hugo Benichi7c342672020-09-08 09:18:14 +09001012 const std::string ifname_id = std::to_string(connected_namespaces_next_id_);
Hugo Benichifcf81022020-12-04 11:01:37 +09001013 ConnectedNamespace nsinfo = {};
1014 nsinfo.pid = request.pid();
1015 nsinfo.netns_name = "connected_netns_" + ifname_id;
Hugo Benichi93306e52020-12-04 16:08:00 +09001016 nsinfo.source = ProtoToTrafficSource(request.traffic_source());
1017 if (nsinfo.source == TrafficSource::UNKNOWN)
1018 nsinfo.source = TrafficSource::SYSTEM;
Hugo Benichifcf81022020-12-04 11:01:37 +09001019 nsinfo.outbound_ifname = request.outbound_physical_device();
Hugo Benichi93306e52020-12-04 16:08:00 +09001020 nsinfo.route_on_vpn = request.route_on_vpn();
Hugo Benichifcf81022020-12-04 11:01:37 +09001021 nsinfo.host_ifname = "arc_ns" + ifname_id;
1022 nsinfo.peer_ifname = "veth" + ifname_id;
1023 nsinfo.peer_subnet = std::move(subnet);
1024 nsinfo.peer_mac_addr = addr_mgr_.GenerateMacAddress();
1025
1026 if (!datapath_->StartRoutingNamespace(nsinfo)) {
Hugo Benichi7c342672020-09-08 09:18:14 +09001027 LOG(ERROR) << "ConnectNamespace: failed to setup datapath";
1028 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL,
1029 local_client_fd.get(), nullptr) != 0)
1030 PLOG(ERROR) << "ConnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
1031 return response;
1032 }
1033
Hugo Benichifcf81022020-12-04 11:01:37 +09001034 // Prepare the response before storing ConnectedNamespace.
1035 response->set_peer_ifname(nsinfo.peer_ifname);
1036 response->set_peer_ipv4_address(nsinfo.peer_subnet->AddressAtOffset(1));
1037 response->set_host_ifname(nsinfo.host_ifname);
1038 response->set_host_ipv4_address(nsinfo.peer_subnet->AddressAtOffset(0));
Hugo Benichi7c342672020-09-08 09:18:14 +09001039 auto* response_subnet = response->mutable_ipv4_subnet();
Hugo Benichifcf81022020-12-04 11:01:37 +09001040 response_subnet->set_base_addr(nsinfo.peer_subnet->BaseAddress());
1041 response_subnet->set_prefix_len(nsinfo.peer_subnet->PrefixLength());
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001042
Hugo Benichifcf81022020-12-04 11:01:37 +09001043 LOG(INFO) << "Connected network namespace " << nsinfo;
1044
1045 // Store ConnectedNamespace
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001046 connected_namespaces_next_id_++;
Hugo Benichi7352ad92020-04-07 16:11:59 +09001047 int fdkey = local_client_fd.release();
Hugo Benichifcf81022020-12-04 11:01:37 +09001048 connected_namespaces_.insert(std::make_pair(fdkey, std::move(nsinfo)));
Hugo Benichi7352ad92020-04-07 16:11:59 +09001049
1050 if (connected_namespaces_.size() == 1) {
1051 LOG(INFO) << "Starting ConnectNamespace client fds monitoring";
1052 CheckConnectedNamespaces();
1053 }
Hugo Benichi7c342672020-09-08 09:18:14 +09001054
1055 return response;
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001056}
1057
1058void Manager::DisconnectNamespace(int client_fd) {
1059 auto it = connected_namespaces_.find(client_fd);
1060 if (it == connected_namespaces_.end()) {
Hugo Benichifcf81022020-12-04 11:01:37 +09001061 LOG(ERROR) << "No ConnectedNamespace found for client_fd " << client_fd;
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001062 return;
1063 }
1064
Hugo Benichi7352ad92020-04-07 16:11:59 +09001065 // Remove the client fd dupe from the epoll watcher and close it.
1066 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL, client_fd,
Hugo Benichie8758b52020-04-03 14:49:01 +09001067 nullptr) != 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +09001068 PLOG(ERROR) << "DisconnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +09001069 if (close(client_fd) < 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +09001070 PLOG(ERROR) << "DisconnectNamespace: close(client_fd) failed";
Hugo Benichi7352ad92020-04-07 16:11:59 +09001071
Hugo Benichifcf81022020-12-04 11:01:37 +09001072 datapath_->StopRoutingNamespace(it->second);
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001073 LOG(INFO) << "Disconnected network namespace " << it->second;
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001074 // This release the allocated IPv4 subnet.
1075 connected_namespaces_.erase(it);
1076}
1077
Hugo Benichi7352ad92020-04-07 16:11:59 +09001078// TODO(hugobenichi) Generalize this check to all resources created by
1079// patchpanel on behalf of a remote client.
1080void Manager::CheckConnectedNamespaces() {
1081 int max_event = 10;
1082 struct epoll_event epevents[max_event];
1083 int nready = epoll_wait(connected_namespaces_epollfd_, epevents, max_event,
1084 0 /* do not block */);
1085 if (nready < 0)
1086 PLOG(ERROR) << "CheckConnectedNamespaces: epoll_wait(0) failed";
1087
1088 for (int i = 0; i < nready; i++)
1089 if (epevents[i].events & (EPOLLHUP | EPOLLERR))
1090 DisconnectNamespace(epevents[i].data.fd);
1091
1092 if (connected_namespaces_.empty()) {
1093 LOG(INFO) << "Stopping ConnectNamespace client fds monitoring";
1094 return;
1095 }
1096
Qijiang Fan2d7aeb42020-05-19 02:06:39 +09001097 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Hugo Benichi7352ad92020-04-07 16:11:59 +09001098 FROM_HERE,
1099 base::Bind(&Manager::CheckConnectedNamespaces,
Hugo Benichie8758b52020-04-03 14:49:01 +09001100 weak_factory_.GetWeakPtr()),
Hugo Benichi7352ad92020-04-07 16:11:59 +09001101 kConnectNamespaceCheckInterval);
1102}
1103
Jason Jeremy Imanc28df852020-07-11 17:38:26 +09001104bool Manager::ModifyPortRule(const patchpanel::ModifyPortRuleRequest& request) {
1105 switch (request.proto()) {
1106 case patchpanel::ModifyPortRuleRequest::TCP:
1107 case patchpanel::ModifyPortRuleRequest::UDP:
1108 break;
1109 default:
1110 LOG(ERROR) << "Unknown protocol " << request.proto();
1111 return false;
1112 }
1113
1114 switch (request.op()) {
1115 case patchpanel::ModifyPortRuleRequest::CREATE:
1116 switch (request.type()) {
1117 case patchpanel::ModifyPortRuleRequest::ACCESS:
1118 return firewall_.AddAcceptRules(request.proto(),
1119 request.input_dst_port(),
1120 request.input_ifname());
1121 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
1122 return firewall_.AddLoopbackLockdownRules(request.proto(),
1123 request.input_dst_port());
1124 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1125 return firewall_.AddIpv4ForwardRule(
1126 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1127 request.input_ifname(), request.dst_ip(), request.dst_port());
1128 default:
1129 LOG(ERROR) << "Unknown port rule type " << request.type();
1130 return false;
1131 }
1132 case patchpanel::ModifyPortRuleRequest::DELETE:
1133 switch (request.type()) {
1134 case patchpanel::ModifyPortRuleRequest::ACCESS:
1135 return firewall_.DeleteAcceptRules(request.proto(),
1136 request.input_dst_port(),
1137 request.input_ifname());
1138 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
1139 return firewall_.DeleteLoopbackLockdownRules(
1140 request.proto(), request.input_dst_port());
1141 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1142 return firewall_.DeleteIpv4ForwardRule(
1143 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1144 request.input_ifname(), request.dst_ip(), request.dst_port());
1145 default:
1146 LOG(ERROR) << "Unknown port rule type " << request.type();
1147 return false;
1148 }
1149 default:
1150 LOG(ERROR) << "Unknown operation " << request.op();
1151 return false;
1152 }
1153}
1154
Garrick Evanse94a14e2019-11-11 10:32:13 +09001155void Manager::SendGuestMessage(const GuestMessage& msg) {
Garrick Evans96e03042019-05-28 14:30:52 +09001156 IpHelperMessage ipm;
1157 *ipm.mutable_guest_message() = msg;
Garrick Evans96e03042019-05-28 14:30:52 +09001158 adb_proxy_->SendMessage(ipm);
Garrick Evanse94a14e2019-11-11 10:32:13 +09001159 mcast_proxy_->SendMessage(ipm);
1160 nd_proxy_->SendMessage(ipm);
Garrick Evans96e03042019-05-28 14:30:52 +09001161}
1162
Garrick Evans4ac09852020-01-16 14:09:22 +09001163void Manager::StartForwarding(const std::string& ifname_physical,
1164 const std::string& ifname_virtual,
Garrick Evans4ac09852020-01-16 14:09:22 +09001165 bool ipv6,
1166 bool multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001167 if (ifname_physical.empty() || ifname_virtual.empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001168 return;
1169
1170 IpHelperMessage ipm;
1171 DeviceMessage* msg = ipm.mutable_device_message();
1172 msg->set_dev_ifname(ifname_physical);
Garrick Evans4ac09852020-01-16 14:09:22 +09001173 msg->set_br_ifname(ifname_virtual);
1174
1175 if (ipv6) {
1176 LOG(INFO) << "Starting IPv6 forwarding from " << ifname_physical << " to "
1177 << ifname_virtual;
1178
1179 if (!datapath_->AddIPv6Forwarding(ifname_physical, ifname_virtual)) {
1180 LOG(ERROR) << "Failed to setup iptables forwarding rule for IPv6 from "
1181 << ifname_physical << " to " << ifname_virtual;
1182 }
1183 if (!datapath_->MaskInterfaceFlags(ifname_physical, IFF_ALLMULTI)) {
1184 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1185 << ifname_physical;
1186 }
1187 if (!datapath_->MaskInterfaceFlags(ifname_virtual, IFF_ALLMULTI)) {
1188 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1189 << ifname_virtual;
1190 }
1191 nd_proxy_->SendMessage(ipm);
1192 }
1193
1194 if (multicast) {
1195 LOG(INFO) << "Starting multicast forwarding from " << ifname_physical
1196 << " to " << ifname_virtual;
1197 mcast_proxy_->SendMessage(ipm);
1198 }
1199}
1200
1201void Manager::StopForwarding(const std::string& ifname_physical,
1202 const std::string& ifname_virtual,
1203 bool ipv6,
1204 bool multicast) {
1205 if (ifname_physical.empty())
1206 return;
1207
1208 IpHelperMessage ipm;
1209 DeviceMessage* msg = ipm.mutable_device_message();
1210 msg->set_dev_ifname(ifname_physical);
1211 msg->set_teardown(true);
Taoyu Li7dca19a2020-03-16 16:27:07 +09001212 if (!ifname_virtual.empty()) {
1213 msg->set_br_ifname(ifname_virtual);
1214 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001215
1216 if (ipv6) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001217 if (ifname_virtual.empty()) {
1218 LOG(INFO) << "Stopping IPv6 forwarding on " << ifname_physical;
1219 } else {
1220 LOG(INFO) << "Stopping IPv6 forwarding from " << ifname_physical << " to "
1221 << ifname_virtual;
1222 datapath_->RemoveIPv6Forwarding(ifname_physical, ifname_virtual);
1223 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001224 nd_proxy_->SendMessage(ipm);
1225 }
1226
1227 if (multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001228 if (ifname_virtual.empty()) {
1229 LOG(INFO) << "Stopping multicast forwarding on " << ifname_physical;
1230 } else {
1231 LOG(INFO) << "Stopping multicast forwarding from " << ifname_physical
1232 << " to " << ifname_virtual;
1233 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001234 mcast_proxy_->SendMessage(ipm);
1235 }
1236}
1237
Taoyu Lia0727dc2020-09-24 19:54:59 +09001238void Manager::OnNDProxyMessage(const NDProxyMessage& msg) {
1239 LOG_IF(DFATAL, msg.ifname().empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001240 << "Received DeviceMessage w/ empty dev_ifname";
Taoyu Lia0727dc2020-09-24 19:54:59 +09001241 switch (msg.type()) {
1242 case NDProxyMessage::ADD_ROUTE:
1243 if (!datapath_->AddIPv6HostRoute(msg.ifname(), msg.ip6addr(), 128)) {
1244 LOG(WARNING) << "Failed to setup the IPv6 route for interface "
1245 << msg.ifname() << ", addr " << msg.ip6addr();
1246 }
1247 break;
1248 case NDProxyMessage::ADD_ADDR:
1249 if (!datapath_->AddIPv6Address(msg.ifname(), msg.ip6addr())) {
1250 LOG(WARNING) << "Failed to setup the IPv6 address for interface "
1251 << msg.ifname() << ", addr " << msg.ip6addr();
1252 }
1253 break;
1254 case NDProxyMessage::DEL_ADDR:
1255 datapath_->RemoveIPv6Address(msg.ifname(), msg.ip6addr());
1256 break;
1257 default:
1258 LOG(ERROR) << "Unknown NDProxy event " << msg.type();
1259 NOTREACHED();
Garrick Evans4ac09852020-01-16 14:09:22 +09001260 }
1261}
1262
Garrick Evans3388a032020-03-24 11:25:55 +09001263} // namespace patchpanel