blob: 2c02a4877dbcc4ef7a768863de59f87017cd2dde [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>
Taoyu Lic85c44b2019-12-04 17:32:57 +090021#include <base/strings/string_number_conversions.h>
Garrick Evans96e03042019-05-28 14:30:52 +090022#include <base/strings/string_split.h>
Garrick Evans6f258d02019-06-28 16:32:07 +090023#include <base/strings/string_util.h>
Taoyu Li179dcc62019-10-17 11:21:08 +090024#include <base/strings/stringprintf.h>
hschamf9546312020-04-14 15:12:40 +090025#include <base/threading/thread_task_runner_handle.h>
Taoyu Lic85c44b2019-12-04 17:32:57 +090026#include <brillo/key_value_store.h>
Kevin Cernekee27bcaa62016-12-03 11:16:26 -080027#include <brillo/minijail/minijail.h>
28
Garrick Evans3388a032020-03-24 11:25:55 +090029#include "patchpanel/ipc.pb.h"
30#include "patchpanel/mac_address_generator.h"
31#include "patchpanel/net_util.h"
32#include "patchpanel/routing_service.h"
33#include "patchpanel/scoped_ns.h"
Garrick Evans428e4762018-12-11 15:18:42 +090034
Garrick Evans3388a032020-03-24 11:25:55 +090035namespace patchpanel {
Garrick Evans08843932019-09-17 14:41:08 +090036namespace {
Garrick Evans4c042572019-12-17 13:42:25 +090037constexpr int kSubprocessRestartDelayMs = 900;
Garrick Evans08843932019-09-17 14:41:08 +090038
Hugo Benichi7352ad92020-04-07 16:11:59 +090039// Time interval between epoll checks on file descriptors committed by callers
40// of ConnectNamespace DBus API.
41constexpr const base::TimeDelta kConnectNamespaceCheckInterval =
Hugo Benichifa9462e2020-06-26 09:50:48 +090042 base::TimeDelta::FromSeconds(5);
Hugo Benichi7352ad92020-04-07 16:11:59 +090043
Garrick Evans08843932019-09-17 14:41:08 +090044// Passes |method_call| to |handler| and passes the response to
45// |response_sender|. If |handler| returns nullptr, an empty response is
46// created and sent.
47void HandleSynchronousDBusMethodCall(
48 base::Callback<std::unique_ptr<dbus::Response>(dbus::MethodCall*)> handler,
49 dbus::MethodCall* method_call,
50 dbus::ExportedObject::ResponseSender response_sender) {
51 std::unique_ptr<dbus::Response> response = handler.Run(method_call);
52 if (!response)
53 response = dbus::Response::FromMethodCall(method_call);
Qijiang Fan0c657d42020-08-24 19:07:50 +090054 std::move(response_sender).Run(std::move(response));
Garrick Evans08843932019-09-17 14:41:08 +090055}
56
57} // namespace
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070058
Taoyu Lice7caa62019-10-01 15:43:33 +090059Manager::Manager(std::unique_ptr<HelperProcess> adb_proxy,
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090060 std::unique_ptr<HelperProcess> mcast_proxy,
Garrick Evans1f5a3612019-11-08 12:59:03 +090061 std::unique_ptr<HelperProcess> nd_proxy)
Garrick Evans3915af32019-07-25 15:44:34 +090062 : adb_proxy_(std::move(adb_proxy)),
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090063 mcast_proxy_(std::move(mcast_proxy)),
Garrick Evans4ee5ce22020-03-18 07:05:17 +090064 nd_proxy_(std::move(nd_proxy)) {
Taoyu Li179dcc62019-10-17 11:21:08 +090065 runner_ = std::make_unique<MinijailedProcessRunner>();
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090066 datapath_ = std::make_unique<Datapath>(runner_.get(), &firewall_);
Hugo Benichi7352ad92020-04-07 16:11:59 +090067 connected_namespaces_epollfd_ = epoll_create(1 /* size */);
Taoyu Li179dcc62019-10-17 11:21:08 +090068}
Long Chengd4415582019-09-24 19:16:09 +000069
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +090070std::map<const std::string, bool> Manager::cached_feature_enabled_ = {};
71
72bool Manager::ShouldEnableFeature(
73 int min_android_sdk_version,
74 int min_chrome_milestone,
75 const std::vector<std::string>& supported_boards,
76 const std::string& feature_name) {
77 static const char kLsbReleasePath[] = "/etc/lsb-release";
78
79 const auto& cached_result = cached_feature_enabled_.find(feature_name);
80 if (cached_result != cached_feature_enabled_.end())
81 return cached_result->second;
82
83 auto check = [min_android_sdk_version, min_chrome_milestone,
84 &supported_boards, &feature_name]() {
85 brillo::KeyValueStore store;
86 if (!store.Load(base::FilePath(kLsbReleasePath))) {
87 LOG(ERROR) << "Could not read lsb-release";
88 return false;
89 }
90
91 std::string value;
92 if (!store.GetString("CHROMEOS_ARC_ANDROID_SDK_VERSION", &value)) {
93 LOG(ERROR) << feature_name
94 << " disabled - cannot determine Android SDK version";
95 return false;
96 }
97 int ver = 0;
98 if (!base::StringToInt(value.c_str(), &ver)) {
99 LOG(ERROR) << feature_name << " disabled - invalid Android SDK version";
100 return false;
101 }
102 if (ver < min_android_sdk_version) {
103 LOG(INFO) << feature_name << " disabled for Android SDK " << value;
104 return false;
105 }
106
107 if (!store.GetString("CHROMEOS_RELEASE_CHROME_MILESTONE", &value)) {
108 LOG(ERROR) << feature_name
109 << " disabled - cannot determine ChromeOS milestone";
110 return false;
111 }
112 if (!base::StringToInt(value.c_str(), &ver)) {
113 LOG(ERROR) << feature_name << " disabled - invalid ChromeOS milestone";
114 return false;
115 }
116 if (ver < min_chrome_milestone) {
117 LOG(INFO) << feature_name << " disabled for ChromeOS milestone " << value;
118 return false;
119 }
120
121 if (!store.GetString("CHROMEOS_RELEASE_BOARD", &value)) {
122 LOG(ERROR) << feature_name << " disabled - cannot determine board";
123 return false;
124 }
125 if (!supported_boards.empty() &&
126 std::find(supported_boards.begin(), supported_boards.end(), value) ==
127 supported_boards.end()) {
128 LOG(INFO) << feature_name << " disabled for board " << value;
129 return false;
130 }
131 return true;
132 };
133
134 bool result = check();
135 cached_feature_enabled_.emplace(feature_name, result);
136 return result;
137}
138
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700139int Manager::OnInit() {
Garrick Evans54861622019-07-19 09:05:09 +0900140 prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800141
142 // Handle subprocess lifecycle.
143 process_reaper_.Register(this);
Hugo Benichi935eca92018-07-03 13:47:24 +0900144
145 CHECK(process_reaper_.WatchForChild(
Garrick Evans96e03042019-05-28 14:30:52 +0900146 FROM_HERE, adb_proxy_->pid(),
147 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
148 adb_proxy_->pid())))
149 << "Failed to watch adb-proxy child process";
Taoyu Liaf944c92019-10-01 12:22:31 +0900150 CHECK(process_reaper_.WatchForChild(
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900151 FROM_HERE, mcast_proxy_->pid(),
152 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
153 nd_proxy_->pid())))
154 << "Failed to watch multicast-proxy child process";
155 CHECK(process_reaper_.WatchForChild(
Taoyu Liaf944c92019-10-01 12:22:31 +0900156 FROM_HERE, nd_proxy_->pid(),
157 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
158 nd_proxy_->pid())))
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900159 << "Failed to watch nd-proxy child process";
Garrick Evans96e03042019-05-28 14:30:52 +0900160
Garrick Evans49879532018-12-03 13:15:36 +0900161 // Run after Daemon::OnInit().
hschamf9546312020-04-14 15:12:40 +0900162 base::ThreadTaskRunnerHandle::Get()->PostTask(
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700163 FROM_HERE,
164 base::Bind(&Manager::InitialSetup, weak_factory_.GetWeakPtr()));
165
166 return DBusDaemon::OnInit();
167}
168
169void Manager::InitialSetup() {
Garrick Evans08843932019-09-17 14:41:08 +0900170 LOG(INFO) << "Setting up DBus service interface";
171 dbus_svc_path_ = bus_->GetExportedObject(
172 dbus::ObjectPath(patchpanel::kPatchPanelServicePath));
173 if (!dbus_svc_path_) {
174 LOG(FATAL) << "Failed to export " << patchpanel::kPatchPanelServicePath
175 << " object";
176 }
177
Hugo Benichi76be34a2020-08-26 22:35:54 +0900178 shill_client_ = std::make_unique<ShillClient>(bus_);
179
Garrick Evans08843932019-09-17 14:41:08 +0900180 using ServiceMethod =
181 std::unique_ptr<dbus::Response> (Manager::*)(dbus::MethodCall*);
182 const std::map<const char*, ServiceMethod> kServiceMethods = {
183 {patchpanel::kArcStartupMethod, &Manager::OnArcStartup},
184 {patchpanel::kArcShutdownMethod, &Manager::OnArcShutdown},
185 {patchpanel::kArcVmStartupMethod, &Manager::OnArcVmStartup},
186 {patchpanel::kArcVmShutdownMethod, &Manager::OnArcVmShutdown},
Garrick Evans47c19272019-11-21 10:58:21 +0900187 {patchpanel::kTerminaVmStartupMethod, &Manager::OnTerminaVmStartup},
188 {patchpanel::kTerminaVmShutdownMethod, &Manager::OnTerminaVmShutdown},
Garrick Evans51d5b552020-01-30 10:42:06 +0900189 {patchpanel::kPluginVmStartupMethod, &Manager::OnPluginVmStartup},
190 {patchpanel::kPluginVmShutdownMethod, &Manager::OnPluginVmShutdown},
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900191 {patchpanel::kSetVpnIntentMethod, &Manager::OnSetVpnIntent},
Hugo Benichib56b77c2020-01-15 16:00:56 +0900192 {patchpanel::kConnectNamespaceMethod, &Manager::OnConnectNamespace},
Jie Jiang493cde42020-07-17 21:43:39 +0900193 {patchpanel::kGetTrafficCountersMethod, &Manager::OnGetTrafficCounters},
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900194 {patchpanel::kModifyPortRuleMethod, &Manager::OnModifyPortRule},
Garrick Evans02e6e872020-11-30 11:53:13 +0900195 {patchpanel::kGetDevicesMethod, &Manager::OnGetDevices},
Garrick Evans08843932019-09-17 14:41:08 +0900196 };
197
198 for (const auto& kv : kServiceMethods) {
199 if (!dbus_svc_path_->ExportMethodAndBlock(
200 patchpanel::kPatchPanelInterface, kv.first,
201 base::Bind(&HandleSynchronousDBusMethodCall,
202 base::Bind(kv.second, base::Unretained(this))))) {
203 LOG(FATAL) << "Failed to export method " << kv.first;
204 }
205 }
206
207 if (!bus_->RequestOwnershipAndBlock(patchpanel::kPatchPanelServiceName,
208 dbus::Bus::REQUIRE_PRIMARY)) {
209 LOG(FATAL) << "Failed to take ownership of "
210 << patchpanel::kPatchPanelServiceName;
211 }
212 LOG(INFO) << "DBus service interface ready";
213
Hugo Benichifda77232020-08-21 18:28:15 +0900214 routing_svc_ = std::make_unique<RoutingService>();
Hugo Benichi058a26a2020-11-26 10:10:39 +0900215 counters_svc_ =
216 std::make_unique<CountersService>(datapath_.get(), runner_.get());
Hugo Benichifda77232020-08-21 18:28:15 +0900217
Hugo Benichibf811c62020-09-07 17:30:45 +0900218 // b/162966185: Allow Jetstream to disable:
219 // - the IP forwarding setup used for hosting VMs and containers,
220 // - the iptables rules for fwmark based routing.
221 if (!USE_JETSTREAM_ROUTING) {
222 datapath_->Start();
Hugo Benichi2a940542020-10-26 18:50:49 +0900223 shill_client_->RegisterDefaultDeviceChangedHandler(base::BindRepeating(
224 &Manager::OnDefaultDeviceChanged, weak_factory_.GetWeakPtr()));
Hugo Benichibf811c62020-09-07 17:30:45 +0900225 shill_client_->RegisterDevicesChangedHandler(base::BindRepeating(
226 &Manager::OnDevicesChanged, weak_factory_.GetWeakPtr()));
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900227 shill_client_->RegisterIPConfigsChangedHandler(base::BindRepeating(
228 &Manager::OnIPConfigsChanged, weak_factory_.GetWeakPtr()));
Hugo Benichibf811c62020-09-07 17:30:45 +0900229 }
Hugo Benichifda77232020-08-21 18:28:15 +0900230
Taoyu Lia0727dc2020-09-24 19:54:59 +0900231 nd_proxy_->RegisterNDProxyMessageHandler(
232 base::Bind(&Manager::OnNDProxyMessage, weak_factory_.GetWeakPtr()));
Hugo Benichifda77232020-08-21 18:28:15 +0900233
Hugo Benichifda77232020-08-21 18:28:15 +0900234 auto* const forwarder = static_cast<TrafficForwarder*>(this);
235
236 GuestMessage::GuestType arc_guest =
237 USE_ARCVM ? GuestMessage::ARC_VM : GuestMessage::ARC;
Garrick Evans209a80a2020-11-30 14:42:40 +0900238 arc_svc_ = std::make_unique<ArcService>(
239 shill_client_.get(), datapath_.get(), &addr_mgr_, forwarder, arc_guest,
240 base::BindRepeating(&Manager::OnDeviceChanged,
241 weak_factory_.GetWeakPtr()));
242 cros_svc_ = std::make_unique<CrostiniService>(
243 shill_client_.get(), &addr_mgr_, datapath_.get(), forwarder,
244 base::BindRepeating(&Manager::OnDeviceChanged,
245 weak_factory_.GetWeakPtr()));
Jie Jiang84966852020-09-18 18:49:05 +0900246 network_monitor_svc_ = std::make_unique<NetworkMonitorService>(
247 shill_client_.get(),
Jie Jiang25c1b972020-11-12 15:42:53 +0900248 base::BindRepeating(&Manager::OnNeighborReachabilityEvent,
Jie Jiang84966852020-09-18 18:49:05 +0900249 weak_factory_.GetWeakPtr()));
Hugo Benichifda77232020-08-21 18:28:15 +0900250 network_monitor_svc_->Start();
Hugo Benichi058a26a2020-11-26 10:10:39 +0900251 counters_svc_->Init(shill_client_->get_devices());
Hugo Benichifda77232020-08-21 18:28:15 +0900252 nd_proxy_->Listen();
253}
254
255void Manager::OnShutdown(int* exit_code) {
256 LOG(INFO) << "Shutting down and cleaning up";
Jie Jiang84966852020-09-18 18:49:05 +0900257 network_monitor_svc_.reset();
Hugo Benichifda77232020-08-21 18:28:15 +0900258 cros_svc_.reset();
259 arc_svc_.reset();
260 close(connected_namespaces_epollfd_);
261 // Tear down any remaining connected namespace.
262 std::vector<int> connected_namespaces_fdkeys;
263 for (const auto& kv : connected_namespaces_)
264 connected_namespaces_fdkeys.push_back(kv.first);
265 for (const int fdkey : connected_namespaces_fdkeys)
266 DisconnectNamespace(fdkey);
Hugo Benichibf811c62020-09-07 17:30:45 +0900267 if (!USE_JETSTREAM_ROUTING)
268 datapath_->Stop();
Jie Jiang00592cf2020-12-17 11:23:49 +0900269
270 brillo::DBusDaemon::OnShutdown(exit_code);
Hugo Benichifda77232020-08-21 18:28:15 +0900271}
272
273void Manager::OnSubprocessExited(pid_t pid, const siginfo_t&) {
274 LOG(ERROR) << "Subprocess " << pid << " exited unexpectedly -"
275 << " attempting to restart";
276
277 HelperProcess* proc;
278 if (pid == adb_proxy_->pid()) {
279 proc = adb_proxy_.get();
280 } else if (pid == mcast_proxy_->pid()) {
281 proc = mcast_proxy_.get();
282 } else if (pid == nd_proxy_->pid()) {
283 proc = nd_proxy_.get();
284 } else {
285 LOG(DFATAL) << "Unknown child process";
286 return;
287 }
288
289 process_reaper_.ForgetChild(pid);
290
291 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
292 FROM_HERE,
293 base::Bind(&Manager::RestartSubprocess, weak_factory_.GetWeakPtr(), proc),
294 base::TimeDelta::FromMilliseconds((2 << proc->restarts()) *
295 kSubprocessRestartDelayMs));
296}
297
298void Manager::RestartSubprocess(HelperProcess* subproc) {
299 if (subproc->Restart()) {
300 DCHECK(process_reaper_.WatchForChild(
301 FROM_HERE, subproc->pid(),
302 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
303 subproc->pid())))
304 << "Failed to watch child process " << subproc->pid();
305 }
306}
307
Hugo Benichi2a940542020-10-26 18:50:49 +0900308void Manager::OnDefaultDeviceChanged(const ShillClient::Device& new_device,
309 const ShillClient::Device& prev_device) {
310 // Only take into account interface switches and ignore layer 3 property
311 // changes.
312 if (prev_device.ifname == new_device.ifname)
313 return;
314
Hugo Benichi058a26a2020-11-26 10:10:39 +0900315 if (prev_device.type == ShillClient::Device::Type::kVPN) {
Hugo Benichi2a940542020-10-26 18:50:49 +0900316 datapath_->StopVpnRouting(prev_device.ifname);
Hugo Benichi058a26a2020-11-26 10:10:39 +0900317 counters_svc_->OnVpnDeviceRemoved(prev_device.ifname);
318 }
Hugo Benichi2a940542020-10-26 18:50:49 +0900319
Hugo Benichi058a26a2020-11-26 10:10:39 +0900320 if (new_device.type == ShillClient::Device::Type::kVPN) {
Hugo Benichi2a940542020-10-26 18:50:49 +0900321 datapath_->StartVpnRouting(new_device.ifname);
Hugo Benichi058a26a2020-11-26 10:10:39 +0900322 counters_svc_->OnVpnDeviceAdded(new_device.ifname);
323 }
Hugo Benichi2a940542020-10-26 18:50:49 +0900324}
325
Hugo Benichi76be34a2020-08-26 22:35:54 +0900326void Manager::OnDevicesChanged(const std::set<std::string>& added,
327 const std::set<std::string>& removed) {
Hugo Benichi058a26a2020-11-26 10:10:39 +0900328 for (const std::string& ifname : removed) {
Hugo Benichi76be34a2020-08-26 22:35:54 +0900329 datapath_->StopConnectionPinning(ifname);
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900330 datapath_->RemoveRedirectDnsRule(ifname);
Hugo Benichi058a26a2020-11-26 10:10:39 +0900331 counters_svc_->OnPhysicalDeviceRemoved(ifname);
332 }
Hugo Benichi76be34a2020-08-26 22:35:54 +0900333
Hugo Benichi058a26a2020-11-26 10:10:39 +0900334 for (const std::string& ifname : added) {
Hugo Benichi76be34a2020-08-26 22:35:54 +0900335 datapath_->StartConnectionPinning(ifname);
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900336 ShillClient::Device device;
337 if (!shill_client_->GetDeviceProperties(ifname, &device))
338 continue;
339
340 if (!device.ipconfig.ipv4_dns_addresses.empty())
341 datapath_->AddRedirectDnsRule(ifname,
342 device.ipconfig.ipv4_dns_addresses.front());
343
Hugo Benichi058a26a2020-11-26 10:10:39 +0900344 counters_svc_->OnPhysicalDeviceAdded(ifname);
345 }
Hugo Benichi76be34a2020-08-26 22:35:54 +0900346}
347
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900348void Manager::OnIPConfigsChanged(const std::string& device,
349 const ShillClient::IPConfig& ipconfig) {
350 if (ipconfig.ipv4_dns_addresses.empty()) {
351 datapath_->RemoveRedirectDnsRule(device);
352 } else {
353 datapath_->AddRedirectDnsRule(device, ipconfig.ipv4_dns_addresses.front());
354 }
355}
356
Garrick Evans209a80a2020-11-30 14:42:40 +0900357void Manager::OnDeviceChanged(const Device& device,
358 Device::ChangeEvent event,
359 GuestMessage::GuestType guest_type) {
360 dbus::Signal signal(kPatchPanelInterface, kNetworkDeviceChangedSignal);
361 NetworkDeviceChangedSignal proto;
362 proto.set_event(event == Device::ChangeEvent::ADDED
363 ? NetworkDeviceChangedSignal::DEVICE_ADDED
364 : NetworkDeviceChangedSignal::DEVICE_REMOVED);
365 auto* dev = proto.mutable_device();
366 dev->set_ifname(device.host_ifname());
367 dev->set_ipv4_addr(device.config().guest_ipv4_addr());
368 if (const auto* subnet = device.config().ipv4_subnet()) {
369 auto* sub = dev->mutable_ipv4_subnet();
370 sub->set_base_addr(subnet->BaseAddress());
371 sub->set_prefix_len(subnet->PrefixLength());
372 }
373 switch (guest_type) {
374 case GuestMessage::ARC:
375 dev->set_guest_type(NetworkDevice::ARC);
376 break;
377 case GuestMessage::ARC_VM:
378 dev->set_guest_type(NetworkDevice::ARCVM);
379 break;
380 case GuestMessage::TERMINA_VM:
381 dev->set_guest_type(NetworkDevice::TERMINA_VM);
382 break;
383 case GuestMessage::PLUGIN_VM:
384 dev->set_guest_type(NetworkDevice::PLUGIN_VM);
385 break;
386 default:
387 LOG(ERROR) << "Unknown device type";
388 }
389
390 dbus::MessageWriter(&signal).AppendProtoAsArrayOfBytes(proto);
391 dbus_svc_path_->SendSignal(&signal);
392}
393
Garrick Evanse94a14e2019-11-11 10:32:13 +0900394bool Manager::StartArc(pid_t pid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900395 if (!arc_svc_->Start(pid))
396 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900397
398 GuestMessage msg;
399 msg.set_event(GuestMessage::START);
400 msg.set_type(GuestMessage::ARC);
401 msg.set_arc_pid(pid);
402 SendGuestMessage(msg);
403
404 return true;
405}
406
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900407void Manager::StopArc() {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900408 GuestMessage msg;
409 msg.set_event(GuestMessage::STOP);
410 msg.set_type(GuestMessage::ARC);
411 SendGuestMessage(msg);
412
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900413 // After the ARC container has stopped, the pid is not known anymore.
414 // The pid argument is ignored by ArcService.
415 arc_svc_->Stop(0);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900416}
417
Garrick Evans015b0d62020-02-07 09:06:38 +0900418bool Manager::StartArcVm(uint32_t cid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900419 if (!arc_svc_->Start(cid))
420 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900421
422 GuestMessage msg;
423 msg.set_event(GuestMessage::START);
424 msg.set_type(GuestMessage::ARC_VM);
425 msg.set_arcvm_vsock_cid(cid);
426 SendGuestMessage(msg);
427
428 return true;
429}
430
Garrick Evans015b0d62020-02-07 09:06:38 +0900431void Manager::StopArcVm(uint32_t cid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900432 GuestMessage msg;
433 msg.set_event(GuestMessage::STOP);
434 msg.set_type(GuestMessage::ARC_VM);
435 SendGuestMessage(msg);
436
Garrick Evans21173b12019-11-20 15:23:16 +0900437 arc_svc_->Stop(cid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900438}
439
Garrick Evans51d5b552020-01-30 10:42:06 +0900440bool Manager::StartCrosVm(uint64_t vm_id,
441 GuestMessage::GuestType vm_type,
Garrick Evans53a2a982020-02-05 10:53:35 +0900442 uint32_t subnet_index) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900443 DCHECK(vm_type == GuestMessage::TERMINA_VM ||
444 vm_type == GuestMessage::PLUGIN_VM);
445
446 if (!cros_svc_->Start(vm_id, vm_type == GuestMessage::TERMINA_VM,
447 subnet_index))
Garrick Evans47c19272019-11-21 10:58:21 +0900448 return false;
449
450 GuestMessage msg;
451 msg.set_event(GuestMessage::START);
Garrick Evans51d5b552020-01-30 10:42:06 +0900452 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900453 SendGuestMessage(msg);
454
455 return true;
456}
457
Garrick Evans51d5b552020-01-30 10:42:06 +0900458void Manager::StopCrosVm(uint64_t vm_id, GuestMessage::GuestType vm_type) {
Garrick Evans47c19272019-11-21 10:58:21 +0900459 GuestMessage msg;
460 msg.set_event(GuestMessage::STOP);
Garrick Evans51d5b552020-01-30 10:42:06 +0900461 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900462 SendGuestMessage(msg);
463
Garrick Evans51d5b552020-01-30 10:42:06 +0900464 cros_svc_->Stop(vm_id, vm_type == GuestMessage::TERMINA_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900465}
466
Garrick Evans02e6e872020-11-30 11:53:13 +0900467std::unique_ptr<dbus::Response> Manager::OnGetDevices(
468 dbus::MethodCall* method_call) {
469 std::unique_ptr<dbus::Response> dbus_response(
470 dbus::Response::FromMethodCall(method_call));
471
472 dbus::MessageReader reader(method_call);
473 dbus::MessageWriter writer(dbus_response.get());
474
475 patchpanel::GetDevicesRequest request;
476 patchpanel::GetDevicesResponse response;
477
478 if (!reader.PopArrayOfBytesAsProto(&request)) {
479 LOG(ERROR) << "Unable to parse request";
480 writer.AppendProtoAsArrayOfBytes(response);
481 return dbus_response;
482 }
483
484 static const auto arc_guest_type =
485 USE_ARCVM ? NetworkDevice::ARCVM : NetworkDevice::ARC;
486
487 arc_svc_->ScanDevices(base::BindRepeating(
488 [](patchpanel::GetDevicesResponse* resp, const Device& device) {
489 auto* dev = resp->add_devices();
490 dev->set_ifname(device.host_ifname());
491 dev->set_ipv4_addr(device.config().guest_ipv4_addr());
492 dev->set_guest_type(arc_guest_type);
493 if (const auto* subnet = device.config().ipv4_subnet()) {
494 auto* sub = dev->mutable_ipv4_subnet();
495 sub->set_base_addr(subnet->BaseAddress());
496 sub->set_prefix_len(subnet->PrefixLength());
497 }
498 },
499 &response));
500
501 cros_svc_->ScanDevices(base::BindRepeating(
502 [](patchpanel::GetDevicesResponse* resp, uint64_t vm_id, bool is_termina,
503 const Device& device) {
504 auto* dev = resp->add_devices();
505 dev->set_ifname(device.host_ifname());
506 dev->set_ipv4_addr(device.config().guest_ipv4_addr());
507 dev->set_guest_type(is_termina ? NetworkDevice::TERMINA_VM
508 : NetworkDevice::PLUGIN_VM);
509 if (const auto* subnet = device.config().ipv4_subnet()) {
510 auto* sub = dev->mutable_ipv4_subnet();
511 sub->set_base_addr(subnet->BaseAddress());
512 sub->set_prefix_len(subnet->PrefixLength());
513 }
514 },
515 &response));
516
517 writer.AppendProtoAsArrayOfBytes(response);
518 return dbus_response;
519}
520
Garrick Evans08843932019-09-17 14:41:08 +0900521std::unique_ptr<dbus::Response> Manager::OnArcStartup(
522 dbus::MethodCall* method_call) {
523 LOG(INFO) << "ARC++ starting up";
524
525 std::unique_ptr<dbus::Response> dbus_response(
526 dbus::Response::FromMethodCall(method_call));
527
528 dbus::MessageReader reader(method_call);
529 dbus::MessageWriter writer(dbus_response.get());
530
531 patchpanel::ArcStartupRequest request;
532 patchpanel::ArcStartupResponse response;
533
534 if (!reader.PopArrayOfBytesAsProto(&request)) {
535 LOG(ERROR) << "Unable to parse request";
536 writer.AppendProtoAsArrayOfBytes(response);
537 return dbus_response;
538 }
539
Garrick Evanse01bf072019-11-15 09:08:19 +0900540 if (!StartArc(request.pid()))
541 LOG(ERROR) << "Failed to start ARC++ network service";
Garrick Evanse94a14e2019-11-11 10:32:13 +0900542
Garrick Evans08843932019-09-17 14:41:08 +0900543 writer.AppendProtoAsArrayOfBytes(response);
544 return dbus_response;
545}
546
547std::unique_ptr<dbus::Response> Manager::OnArcShutdown(
548 dbus::MethodCall* method_call) {
549 LOG(INFO) << "ARC++ shutting down";
550
551 std::unique_ptr<dbus::Response> dbus_response(
552 dbus::Response::FromMethodCall(method_call));
553
554 dbus::MessageReader reader(method_call);
555 dbus::MessageWriter writer(dbus_response.get());
556
557 patchpanel::ArcShutdownRequest request;
558 patchpanel::ArcShutdownResponse response;
559
560 if (!reader.PopArrayOfBytesAsProto(&request)) {
561 LOG(ERROR) << "Unable to parse request";
562 writer.AppendProtoAsArrayOfBytes(response);
563 return dbus_response;
564 }
565
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900566 StopArc();
Garrick Evanse94a14e2019-11-11 10:32:13 +0900567
Garrick Evans08843932019-09-17 14:41:08 +0900568 writer.AppendProtoAsArrayOfBytes(response);
569 return dbus_response;
570}
571
572std::unique_ptr<dbus::Response> Manager::OnArcVmStartup(
573 dbus::MethodCall* method_call) {
574 LOG(INFO) << "ARCVM starting up";
575
576 std::unique_ptr<dbus::Response> dbus_response(
577 dbus::Response::FromMethodCall(method_call));
578
579 dbus::MessageReader reader(method_call);
580 dbus::MessageWriter writer(dbus_response.get());
581
582 patchpanel::ArcVmStartupRequest request;
583 patchpanel::ArcVmStartupResponse response;
584
585 if (!reader.PopArrayOfBytesAsProto(&request)) {
586 LOG(ERROR) << "Unable to parse request";
587 writer.AppendProtoAsArrayOfBytes(response);
588 return dbus_response;
589 }
590
Garrick Evans47c19272019-11-21 10:58:21 +0900591 if (!StartArcVm(request.cid())) {
Garrick Evanse01bf072019-11-15 09:08:19 +0900592 LOG(ERROR) << "Failed to start ARCVM network service";
Garrick Evans47c19272019-11-21 10:58:21 +0900593 writer.AppendProtoAsArrayOfBytes(response);
594 return dbus_response;
Garrick Evanse01bf072019-11-15 09:08:19 +0900595 }
Garrick Evanse94a14e2019-11-11 10:32:13 +0900596
Garrick Evans47c19272019-11-21 10:58:21 +0900597 // Populate the response with the known devices.
Garrick Evans38b25a42020-04-06 15:17:42 +0900598 for (const auto* config : arc_svc_->GetDeviceConfigs()) {
599 if (config->tap_ifname().empty())
600 continue;
Garrick Evans47c19272019-11-21 10:58:21 +0900601
Garrick Evans38b25a42020-04-06 15:17:42 +0900602 auto* dev = response.add_devices();
603 dev->set_ifname(config->tap_ifname());
604 dev->set_ipv4_addr(config->guest_ipv4_addr());
Garrick Evansa0c9c972020-11-30 09:54:59 +0900605 dev->set_guest_type(NetworkDevice::ARCVM);
Garrick Evans38b25a42020-04-06 15:17:42 +0900606 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900607
Garrick Evans08843932019-09-17 14:41:08 +0900608 writer.AppendProtoAsArrayOfBytes(response);
609 return dbus_response;
610}
611
612std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
613 dbus::MethodCall* method_call) {
614 LOG(INFO) << "ARCVM shutting down";
615
616 std::unique_ptr<dbus::Response> dbus_response(
617 dbus::Response::FromMethodCall(method_call));
618
619 dbus::MessageReader reader(method_call);
620 dbus::MessageWriter writer(dbus_response.get());
621
622 patchpanel::ArcVmShutdownRequest request;
623 patchpanel::ArcVmShutdownResponse response;
624
625 if (!reader.PopArrayOfBytesAsProto(&request)) {
626 LOG(ERROR) << "Unable to parse request";
627 writer.AppendProtoAsArrayOfBytes(response);
628 return dbus_response;
629 }
630
Garrick Evans21173b12019-11-20 15:23:16 +0900631 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900632
Garrick Evans08843932019-09-17 14:41:08 +0900633 writer.AppendProtoAsArrayOfBytes(response);
634 return dbus_response;
635}
636
Garrick Evans47c19272019-11-21 10:58:21 +0900637std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
638 dbus::MethodCall* method_call) {
639 LOG(INFO) << "Termina VM starting up";
640
641 std::unique_ptr<dbus::Response> dbus_response(
642 dbus::Response::FromMethodCall(method_call));
643
644 dbus::MessageReader reader(method_call);
645 dbus::MessageWriter writer(dbus_response.get());
646
647 patchpanel::TerminaVmStartupRequest request;
648 patchpanel::TerminaVmStartupResponse response;
649
650 if (!reader.PopArrayOfBytesAsProto(&request)) {
651 LOG(ERROR) << "Unable to parse request";
652 writer.AppendProtoAsArrayOfBytes(response);
653 return dbus_response;
654 }
655
656 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900657 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900658 LOG(ERROR) << "Failed to start Termina VM network service";
659 writer.AppendProtoAsArrayOfBytes(response);
660 return dbus_response;
661 }
662
Garrick Evans51d5b552020-01-30 10:42:06 +0900663 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900664 if (!tap) {
665 LOG(DFATAL) << "TAP device missing";
666 writer.AppendProtoAsArrayOfBytes(response);
667 return dbus_response;
668 }
Garrick Evans47c19272019-11-21 10:58:21 +0900669
Garrick Evansb1c93712020-01-22 09:28:25 +0900670 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900671 dev->set_ifname(tap->host_ifname());
Garrick Evansa0c9c972020-11-30 09:54:59 +0900672 dev->set_guest_type(NetworkDevice::TERMINA_VM);
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900673 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900674 if (!subnet) {
675 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
676 writer.AppendProtoAsArrayOfBytes(response);
677 return dbus_response;
678 }
679 auto* resp_subnet = dev->mutable_ipv4_subnet();
680 resp_subnet->set_base_addr(subnet->BaseAddress());
681 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900682 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900683 if (!subnet) {
684 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
685 writer.AppendProtoAsArrayOfBytes(response);
686 return dbus_response;
687 }
688 resp_subnet = response.mutable_container_subnet();
689 resp_subnet->set_base_addr(subnet->BaseAddress());
690 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900691
692 writer.AppendProtoAsArrayOfBytes(response);
693 return dbus_response;
694}
695
696std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
697 dbus::MethodCall* method_call) {
698 LOG(INFO) << "Termina VM shutting down";
699
700 std::unique_ptr<dbus::Response> dbus_response(
701 dbus::Response::FromMethodCall(method_call));
702
703 dbus::MessageReader reader(method_call);
704 dbus::MessageWriter writer(dbus_response.get());
705
706 patchpanel::TerminaVmShutdownRequest request;
707 patchpanel::TerminaVmShutdownResponse response;
708
709 if (!reader.PopArrayOfBytesAsProto(&request)) {
710 LOG(ERROR) << "Unable to parse request";
711 writer.AppendProtoAsArrayOfBytes(response);
712 return dbus_response;
713 }
714
Garrick Evans51d5b552020-01-30 10:42:06 +0900715 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
716
717 writer.AppendProtoAsArrayOfBytes(response);
718 return dbus_response;
719}
720
721std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
722 dbus::MethodCall* method_call) {
723 LOG(INFO) << "Plugin VM starting up";
724
725 std::unique_ptr<dbus::Response> dbus_response(
726 dbus::Response::FromMethodCall(method_call));
727
728 dbus::MessageReader reader(method_call);
729 dbus::MessageWriter writer(dbus_response.get());
730
731 patchpanel::PluginVmStartupRequest request;
732 patchpanel::PluginVmStartupResponse response;
733
734 if (!reader.PopArrayOfBytesAsProto(&request)) {
735 LOG(ERROR) << "Unable to parse request";
736 writer.AppendProtoAsArrayOfBytes(response);
737 return dbus_response;
738 }
739
Garrick Evans08fb34b2020-02-20 10:50:17 +0900740 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900741 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900742 LOG(ERROR) << "Failed to start Plugin VM network service";
743 writer.AppendProtoAsArrayOfBytes(response);
744 return dbus_response;
745 }
746
747 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
748 if (!tap) {
749 LOG(DFATAL) << "TAP device missing";
750 writer.AppendProtoAsArrayOfBytes(response);
751 return dbus_response;
752 }
753
Garrick Evans51d5b552020-01-30 10:42:06 +0900754 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900755 dev->set_ifname(tap->host_ifname());
Garrick Evansa0c9c972020-11-30 09:54:59 +0900756 dev->set_guest_type(NetworkDevice::PLUGIN_VM);
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900757 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900758 if (!subnet) {
759 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
760 writer.AppendProtoAsArrayOfBytes(response);
761 return dbus_response;
762 }
763 auto* resp_subnet = dev->mutable_ipv4_subnet();
764 resp_subnet->set_base_addr(subnet->BaseAddress());
765 resp_subnet->set_prefix_len(subnet->PrefixLength());
766
767 writer.AppendProtoAsArrayOfBytes(response);
768 return dbus_response;
769}
770
771std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
772 dbus::MethodCall* method_call) {
773 LOG(INFO) << "Plugin VM shutting down";
774
775 std::unique_ptr<dbus::Response> dbus_response(
776 dbus::Response::FromMethodCall(method_call));
777
778 dbus::MessageReader reader(method_call);
779 dbus::MessageWriter writer(dbus_response.get());
780
781 patchpanel::PluginVmShutdownRequest request;
782 patchpanel::PluginVmShutdownResponse response;
783
784 if (!reader.PopArrayOfBytesAsProto(&request)) {
785 LOG(ERROR) << "Unable to parse request";
786 writer.AppendProtoAsArrayOfBytes(response);
787 return dbus_response;
788 }
789
790 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900791
792 writer.AppendProtoAsArrayOfBytes(response);
793 return dbus_response;
794}
795
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900796std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
797 dbus::MethodCall* method_call) {
798 std::unique_ptr<dbus::Response> dbus_response(
799 dbus::Response::FromMethodCall(method_call));
800
801 dbus::MessageReader reader(method_call);
802 dbus::MessageWriter writer(dbus_response.get());
803
804 patchpanel::SetVpnIntentRequest request;
805 patchpanel::SetVpnIntentResponse response;
806
807 bool success = reader.PopArrayOfBytesAsProto(&request);
808 if (!success) {
809 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
810 // Do not return yet to make sure we close the received fd.
811 }
812
813 base::ScopedFD client_socket;
814 reader.PopFileDescriptor(&client_socket);
815
816 if (success)
817 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
818
819 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900820
821 writer.AppendProtoAsArrayOfBytes(response);
822 return dbus_response;
823}
824
825std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
826 dbus::MethodCall* method_call) {
827 std::unique_ptr<dbus::Response> dbus_response(
828 dbus::Response::FromMethodCall(method_call));
829
830 dbus::MessageReader reader(method_call);
831 dbus::MessageWriter writer(dbus_response.get());
832
833 patchpanel::ConnectNamespaceRequest request;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900834
835 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900836 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
837 // Do not return yet to make sure we close the received fd and
838 // validate other arguments.
Hugo Benichi7c342672020-09-08 09:18:14 +0900839 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
840 return dbus_response;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900841 }
842
Hugo Benichicc6850f2020-01-17 13:26:06 +0900843 base::ScopedFD client_fd;
844 reader.PopFileDescriptor(&client_fd);
845 if (!client_fd.is_valid()) {
846 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
Hugo Benichi7c342672020-09-08 09:18:14 +0900847 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
848 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900849 }
850
851 pid_t pid = request.pid();
Garrick Evans263bd952020-12-03 20:27:43 +0900852 if (pid == 1 || pid == getpid()) {
853 LOG(ERROR) << "ConnectNamespaceRequest: privileged namespace pid " << pid;
854 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
855 return dbus_response;
856 }
Hugo Benichicc6850f2020-01-17 13:26:06 +0900857 {
858 ScopedNS ns(pid);
859 if (!ns.IsValid()) {
860 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900861 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
862 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900863 }
864 }
865
866 const std::string& outbound_ifname = request.outbound_physical_device();
867 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
868 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
869 << outbound_ifname;
Hugo Benichi7c342672020-09-08 09:18:14 +0900870 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
871 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900872 }
873
Hugo Benichi7c342672020-09-08 09:18:14 +0900874 auto response = ConnectNamespace(std::move(client_fd), request);
875 writer.AppendProtoAsArrayOfBytes(*response);
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900876 return dbus_response;
877}
878
Jie Jiang493cde42020-07-17 21:43:39 +0900879std::unique_ptr<dbus::Response> Manager::OnGetTrafficCounters(
880 dbus::MethodCall* method_call) {
881 std::unique_ptr<dbus::Response> dbus_response(
882 dbus::Response::FromMethodCall(method_call));
883
884 dbus::MessageReader reader(method_call);
885 dbus::MessageWriter writer(dbus_response.get());
886
887 patchpanel::TrafficCountersRequest request;
888 patchpanel::TrafficCountersResponse response;
889
890 if (!reader.PopArrayOfBytesAsProto(&request)) {
891 LOG(ERROR) << "Unable to parse TrafficCountersRequest";
892 writer.AppendProtoAsArrayOfBytes(response);
893 return dbus_response;
894 }
895
896 const std::set<std::string> devices{request.devices().begin(),
897 request.devices().end()};
Hugo Benichi1df64172020-12-13 22:59:01 +0900898 // TODO(b/175364240) Find why iptables -L -x -v -w can freeze on
899 // writing to stdout and in turn block patchpanel.
900 /*
Jie Jiang493cde42020-07-17 21:43:39 +0900901 const auto counters = counters_svc_->GetCounters(devices);
902 for (const auto& kv : counters) {
903 auto* traffic_counter = response.add_counters();
904 const auto& source_and_device = kv.first;
905 const auto& counter = kv.second;
906 traffic_counter->set_source(source_and_device.first);
907 traffic_counter->set_device(source_and_device.second);
908 traffic_counter->set_rx_bytes(counter.rx_bytes);
909 traffic_counter->set_rx_packets(counter.rx_packets);
910 traffic_counter->set_tx_bytes(counter.tx_bytes);
911 traffic_counter->set_tx_packets(counter.tx_packets);
912 }
Hugo Benichi1df64172020-12-13 22:59:01 +0900913 */
Jie Jiang493cde42020-07-17 21:43:39 +0900914
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