blob: c562e3417116f500eb28a3ad5eee5d6a20408d2e [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());
Garrick Evans9ccd2a62021-02-18 14:48:28 +0900367 dev->set_phys_ifname(device.phys_ifname());
Garrick Evans209a80a2020-11-30 14:42:40 +0900368 dev->set_ipv4_addr(device.config().guest_ipv4_addr());
369 if (const auto* subnet = device.config().ipv4_subnet()) {
370 auto* sub = dev->mutable_ipv4_subnet();
371 sub->set_base_addr(subnet->BaseAddress());
372 sub->set_prefix_len(subnet->PrefixLength());
373 }
374 switch (guest_type) {
375 case GuestMessage::ARC:
376 dev->set_guest_type(NetworkDevice::ARC);
377 break;
378 case GuestMessage::ARC_VM:
379 dev->set_guest_type(NetworkDevice::ARCVM);
380 break;
381 case GuestMessage::TERMINA_VM:
382 dev->set_guest_type(NetworkDevice::TERMINA_VM);
383 break;
384 case GuestMessage::PLUGIN_VM:
385 dev->set_guest_type(NetworkDevice::PLUGIN_VM);
386 break;
387 default:
388 LOG(ERROR) << "Unknown device type";
389 }
390
391 dbus::MessageWriter(&signal).AppendProtoAsArrayOfBytes(proto);
392 dbus_svc_path_->SendSignal(&signal);
393}
394
Garrick Evanse94a14e2019-11-11 10:32:13 +0900395bool Manager::StartArc(pid_t pid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900396 if (!arc_svc_->Start(pid))
397 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900398
399 GuestMessage msg;
400 msg.set_event(GuestMessage::START);
401 msg.set_type(GuestMessage::ARC);
402 msg.set_arc_pid(pid);
403 SendGuestMessage(msg);
404
405 return true;
406}
407
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900408void Manager::StopArc() {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900409 GuestMessage msg;
410 msg.set_event(GuestMessage::STOP);
411 msg.set_type(GuestMessage::ARC);
412 SendGuestMessage(msg);
413
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900414 // After the ARC container has stopped, the pid is not known anymore.
415 // The pid argument is ignored by ArcService.
416 arc_svc_->Stop(0);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900417}
418
Garrick Evans015b0d62020-02-07 09:06:38 +0900419bool Manager::StartArcVm(uint32_t cid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900420 if (!arc_svc_->Start(cid))
421 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900422
423 GuestMessage msg;
424 msg.set_event(GuestMessage::START);
425 msg.set_type(GuestMessage::ARC_VM);
426 msg.set_arcvm_vsock_cid(cid);
427 SendGuestMessage(msg);
428
429 return true;
430}
431
Garrick Evans015b0d62020-02-07 09:06:38 +0900432void Manager::StopArcVm(uint32_t cid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900433 GuestMessage msg;
434 msg.set_event(GuestMessage::STOP);
435 msg.set_type(GuestMessage::ARC_VM);
436 SendGuestMessage(msg);
437
Garrick Evans21173b12019-11-20 15:23:16 +0900438 arc_svc_->Stop(cid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900439}
440
Garrick Evans51d5b552020-01-30 10:42:06 +0900441bool Manager::StartCrosVm(uint64_t vm_id,
442 GuestMessage::GuestType vm_type,
Garrick Evans53a2a982020-02-05 10:53:35 +0900443 uint32_t subnet_index) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900444 DCHECK(vm_type == GuestMessage::TERMINA_VM ||
445 vm_type == GuestMessage::PLUGIN_VM);
446
447 if (!cros_svc_->Start(vm_id, vm_type == GuestMessage::TERMINA_VM,
448 subnet_index))
Garrick Evans47c19272019-11-21 10:58:21 +0900449 return false;
450
451 GuestMessage msg;
452 msg.set_event(GuestMessage::START);
Garrick Evans51d5b552020-01-30 10:42:06 +0900453 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900454 SendGuestMessage(msg);
455
456 return true;
457}
458
Garrick Evans51d5b552020-01-30 10:42:06 +0900459void Manager::StopCrosVm(uint64_t vm_id, GuestMessage::GuestType vm_type) {
Garrick Evans47c19272019-11-21 10:58:21 +0900460 GuestMessage msg;
461 msg.set_event(GuestMessage::STOP);
Garrick Evans51d5b552020-01-30 10:42:06 +0900462 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900463 SendGuestMessage(msg);
464
Garrick Evans51d5b552020-01-30 10:42:06 +0900465 cros_svc_->Stop(vm_id, vm_type == GuestMessage::TERMINA_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900466}
467
Garrick Evans02e6e872020-11-30 11:53:13 +0900468std::unique_ptr<dbus::Response> Manager::OnGetDevices(
469 dbus::MethodCall* method_call) {
470 std::unique_ptr<dbus::Response> dbus_response(
471 dbus::Response::FromMethodCall(method_call));
472
473 dbus::MessageReader reader(method_call);
474 dbus::MessageWriter writer(dbus_response.get());
475
476 patchpanel::GetDevicesRequest request;
477 patchpanel::GetDevicesResponse response;
478
479 if (!reader.PopArrayOfBytesAsProto(&request)) {
480 LOG(ERROR) << "Unable to parse request";
481 writer.AppendProtoAsArrayOfBytes(response);
482 return dbus_response;
483 }
484
485 static const auto arc_guest_type =
486 USE_ARCVM ? NetworkDevice::ARCVM : NetworkDevice::ARC;
487
488 arc_svc_->ScanDevices(base::BindRepeating(
489 [](patchpanel::GetDevicesResponse* resp, const Device& device) {
490 auto* dev = resp->add_devices();
491 dev->set_ifname(device.host_ifname());
Garrick Evans9ccd2a62021-02-18 14:48:28 +0900492 dev->set_phys_ifname(device.phys_ifname());
Garrick Evans02e6e872020-11-30 11:53:13 +0900493 dev->set_ipv4_addr(device.config().guest_ipv4_addr());
494 dev->set_guest_type(arc_guest_type);
495 if (const auto* subnet = device.config().ipv4_subnet()) {
496 auto* sub = dev->mutable_ipv4_subnet();
497 sub->set_base_addr(subnet->BaseAddress());
498 sub->set_prefix_len(subnet->PrefixLength());
499 }
500 },
501 &response));
502
503 cros_svc_->ScanDevices(base::BindRepeating(
504 [](patchpanel::GetDevicesResponse* resp, uint64_t vm_id, bool is_termina,
505 const Device& device) {
506 auto* dev = resp->add_devices();
507 dev->set_ifname(device.host_ifname());
Garrick Evans9ccd2a62021-02-18 14:48:28 +0900508 dev->set_phys_ifname(device.phys_ifname());
Garrick Evans02e6e872020-11-30 11:53:13 +0900509 dev->set_ipv4_addr(device.config().guest_ipv4_addr());
510 dev->set_guest_type(is_termina ? NetworkDevice::TERMINA_VM
511 : NetworkDevice::PLUGIN_VM);
512 if (const auto* subnet = device.config().ipv4_subnet()) {
513 auto* sub = dev->mutable_ipv4_subnet();
514 sub->set_base_addr(subnet->BaseAddress());
515 sub->set_prefix_len(subnet->PrefixLength());
516 }
517 },
518 &response));
519
520 writer.AppendProtoAsArrayOfBytes(response);
521 return dbus_response;
522}
523
Garrick Evans08843932019-09-17 14:41:08 +0900524std::unique_ptr<dbus::Response> Manager::OnArcStartup(
525 dbus::MethodCall* method_call) {
526 LOG(INFO) << "ARC++ starting up";
527
528 std::unique_ptr<dbus::Response> dbus_response(
529 dbus::Response::FromMethodCall(method_call));
530
531 dbus::MessageReader reader(method_call);
532 dbus::MessageWriter writer(dbus_response.get());
533
534 patchpanel::ArcStartupRequest request;
535 patchpanel::ArcStartupResponse response;
536
537 if (!reader.PopArrayOfBytesAsProto(&request)) {
538 LOG(ERROR) << "Unable to parse request";
539 writer.AppendProtoAsArrayOfBytes(response);
540 return dbus_response;
541 }
542
Garrick Evanse01bf072019-11-15 09:08:19 +0900543 if (!StartArc(request.pid()))
544 LOG(ERROR) << "Failed to start ARC++ network service";
Garrick Evanse94a14e2019-11-11 10:32:13 +0900545
Garrick Evans08843932019-09-17 14:41:08 +0900546 writer.AppendProtoAsArrayOfBytes(response);
547 return dbus_response;
548}
549
550std::unique_ptr<dbus::Response> Manager::OnArcShutdown(
551 dbus::MethodCall* method_call) {
552 LOG(INFO) << "ARC++ shutting down";
553
554 std::unique_ptr<dbus::Response> dbus_response(
555 dbus::Response::FromMethodCall(method_call));
556
557 dbus::MessageReader reader(method_call);
558 dbus::MessageWriter writer(dbus_response.get());
559
560 patchpanel::ArcShutdownRequest request;
561 patchpanel::ArcShutdownResponse response;
562
563 if (!reader.PopArrayOfBytesAsProto(&request)) {
564 LOG(ERROR) << "Unable to parse request";
565 writer.AppendProtoAsArrayOfBytes(response);
566 return dbus_response;
567 }
568
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900569 StopArc();
Garrick Evanse94a14e2019-11-11 10:32:13 +0900570
Garrick Evans08843932019-09-17 14:41:08 +0900571 writer.AppendProtoAsArrayOfBytes(response);
572 return dbus_response;
573}
574
575std::unique_ptr<dbus::Response> Manager::OnArcVmStartup(
576 dbus::MethodCall* method_call) {
577 LOG(INFO) << "ARCVM starting up";
578
579 std::unique_ptr<dbus::Response> dbus_response(
580 dbus::Response::FromMethodCall(method_call));
581
582 dbus::MessageReader reader(method_call);
583 dbus::MessageWriter writer(dbus_response.get());
584
585 patchpanel::ArcVmStartupRequest request;
586 patchpanel::ArcVmStartupResponse response;
587
588 if (!reader.PopArrayOfBytesAsProto(&request)) {
589 LOG(ERROR) << "Unable to parse request";
590 writer.AppendProtoAsArrayOfBytes(response);
591 return dbus_response;
592 }
593
Garrick Evans47c19272019-11-21 10:58:21 +0900594 if (!StartArcVm(request.cid())) {
Garrick Evanse01bf072019-11-15 09:08:19 +0900595 LOG(ERROR) << "Failed to start ARCVM network service";
Garrick Evans47c19272019-11-21 10:58:21 +0900596 writer.AppendProtoAsArrayOfBytes(response);
597 return dbus_response;
Garrick Evanse01bf072019-11-15 09:08:19 +0900598 }
Garrick Evanse94a14e2019-11-11 10:32:13 +0900599
Garrick Evans47c19272019-11-21 10:58:21 +0900600 // Populate the response with the known devices.
Garrick Evans38b25a42020-04-06 15:17:42 +0900601 for (const auto* config : arc_svc_->GetDeviceConfigs()) {
602 if (config->tap_ifname().empty())
603 continue;
Garrick Evans47c19272019-11-21 10:58:21 +0900604
Garrick Evans38b25a42020-04-06 15:17:42 +0900605 auto* dev = response.add_devices();
606 dev->set_ifname(config->tap_ifname());
607 dev->set_ipv4_addr(config->guest_ipv4_addr());
Garrick Evansa0c9c972020-11-30 09:54:59 +0900608 dev->set_guest_type(NetworkDevice::ARCVM);
Garrick Evans38b25a42020-04-06 15:17:42 +0900609 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900610
Garrick Evans08843932019-09-17 14:41:08 +0900611 writer.AppendProtoAsArrayOfBytes(response);
612 return dbus_response;
613}
614
615std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
616 dbus::MethodCall* method_call) {
617 LOG(INFO) << "ARCVM shutting down";
618
619 std::unique_ptr<dbus::Response> dbus_response(
620 dbus::Response::FromMethodCall(method_call));
621
622 dbus::MessageReader reader(method_call);
623 dbus::MessageWriter writer(dbus_response.get());
624
625 patchpanel::ArcVmShutdownRequest request;
626 patchpanel::ArcVmShutdownResponse response;
627
628 if (!reader.PopArrayOfBytesAsProto(&request)) {
629 LOG(ERROR) << "Unable to parse request";
630 writer.AppendProtoAsArrayOfBytes(response);
631 return dbus_response;
632 }
633
Garrick Evans21173b12019-11-20 15:23:16 +0900634 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900635
Garrick Evans08843932019-09-17 14:41:08 +0900636 writer.AppendProtoAsArrayOfBytes(response);
637 return dbus_response;
638}
639
Garrick Evans47c19272019-11-21 10:58:21 +0900640std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
641 dbus::MethodCall* method_call) {
642 LOG(INFO) << "Termina VM starting up";
643
644 std::unique_ptr<dbus::Response> dbus_response(
645 dbus::Response::FromMethodCall(method_call));
646
647 dbus::MessageReader reader(method_call);
648 dbus::MessageWriter writer(dbus_response.get());
649
650 patchpanel::TerminaVmStartupRequest request;
651 patchpanel::TerminaVmStartupResponse response;
652
653 if (!reader.PopArrayOfBytesAsProto(&request)) {
654 LOG(ERROR) << "Unable to parse request";
655 writer.AppendProtoAsArrayOfBytes(response);
656 return dbus_response;
657 }
658
659 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900660 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900661 LOG(ERROR) << "Failed to start Termina VM network service";
662 writer.AppendProtoAsArrayOfBytes(response);
663 return dbus_response;
664 }
665
Garrick Evans51d5b552020-01-30 10:42:06 +0900666 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900667 if (!tap) {
668 LOG(DFATAL) << "TAP device missing";
669 writer.AppendProtoAsArrayOfBytes(response);
670 return dbus_response;
671 }
Garrick Evans47c19272019-11-21 10:58:21 +0900672
Garrick Evansb1c93712020-01-22 09:28:25 +0900673 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900674 dev->set_ifname(tap->host_ifname());
Garrick Evansa0c9c972020-11-30 09:54:59 +0900675 dev->set_guest_type(NetworkDevice::TERMINA_VM);
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900676 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900677 if (!subnet) {
678 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
679 writer.AppendProtoAsArrayOfBytes(response);
680 return dbus_response;
681 }
682 auto* resp_subnet = dev->mutable_ipv4_subnet();
683 resp_subnet->set_base_addr(subnet->BaseAddress());
684 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900685 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900686 if (!subnet) {
687 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
688 writer.AppendProtoAsArrayOfBytes(response);
689 return dbus_response;
690 }
691 resp_subnet = response.mutable_container_subnet();
692 resp_subnet->set_base_addr(subnet->BaseAddress());
693 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900694
695 writer.AppendProtoAsArrayOfBytes(response);
696 return dbus_response;
697}
698
699std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
700 dbus::MethodCall* method_call) {
701 LOG(INFO) << "Termina VM shutting down";
702
703 std::unique_ptr<dbus::Response> dbus_response(
704 dbus::Response::FromMethodCall(method_call));
705
706 dbus::MessageReader reader(method_call);
707 dbus::MessageWriter writer(dbus_response.get());
708
709 patchpanel::TerminaVmShutdownRequest request;
710 patchpanel::TerminaVmShutdownResponse response;
711
712 if (!reader.PopArrayOfBytesAsProto(&request)) {
713 LOG(ERROR) << "Unable to parse request";
714 writer.AppendProtoAsArrayOfBytes(response);
715 return dbus_response;
716 }
717
Garrick Evans51d5b552020-01-30 10:42:06 +0900718 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
719
720 writer.AppendProtoAsArrayOfBytes(response);
721 return dbus_response;
722}
723
724std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
725 dbus::MethodCall* method_call) {
726 LOG(INFO) << "Plugin VM starting up";
727
728 std::unique_ptr<dbus::Response> dbus_response(
729 dbus::Response::FromMethodCall(method_call));
730
731 dbus::MessageReader reader(method_call);
732 dbus::MessageWriter writer(dbus_response.get());
733
734 patchpanel::PluginVmStartupRequest request;
735 patchpanel::PluginVmStartupResponse response;
736
737 if (!reader.PopArrayOfBytesAsProto(&request)) {
738 LOG(ERROR) << "Unable to parse request";
739 writer.AppendProtoAsArrayOfBytes(response);
740 return dbus_response;
741 }
742
Garrick Evans08fb34b2020-02-20 10:50:17 +0900743 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900744 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900745 LOG(ERROR) << "Failed to start Plugin VM network service";
746 writer.AppendProtoAsArrayOfBytes(response);
747 return dbus_response;
748 }
749
750 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
751 if (!tap) {
752 LOG(DFATAL) << "TAP device missing";
753 writer.AppendProtoAsArrayOfBytes(response);
754 return dbus_response;
755 }
756
Garrick Evans51d5b552020-01-30 10:42:06 +0900757 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900758 dev->set_ifname(tap->host_ifname());
Garrick Evansa0c9c972020-11-30 09:54:59 +0900759 dev->set_guest_type(NetworkDevice::PLUGIN_VM);
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900760 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900761 if (!subnet) {
762 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
763 writer.AppendProtoAsArrayOfBytes(response);
764 return dbus_response;
765 }
766 auto* resp_subnet = dev->mutable_ipv4_subnet();
767 resp_subnet->set_base_addr(subnet->BaseAddress());
768 resp_subnet->set_prefix_len(subnet->PrefixLength());
769
770 writer.AppendProtoAsArrayOfBytes(response);
771 return dbus_response;
772}
773
774std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
775 dbus::MethodCall* method_call) {
776 LOG(INFO) << "Plugin VM shutting down";
777
778 std::unique_ptr<dbus::Response> dbus_response(
779 dbus::Response::FromMethodCall(method_call));
780
781 dbus::MessageReader reader(method_call);
782 dbus::MessageWriter writer(dbus_response.get());
783
784 patchpanel::PluginVmShutdownRequest request;
785 patchpanel::PluginVmShutdownResponse response;
786
787 if (!reader.PopArrayOfBytesAsProto(&request)) {
788 LOG(ERROR) << "Unable to parse request";
789 writer.AppendProtoAsArrayOfBytes(response);
790 return dbus_response;
791 }
792
793 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900794
795 writer.AppendProtoAsArrayOfBytes(response);
796 return dbus_response;
797}
798
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900799std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
800 dbus::MethodCall* method_call) {
801 std::unique_ptr<dbus::Response> dbus_response(
802 dbus::Response::FromMethodCall(method_call));
803
804 dbus::MessageReader reader(method_call);
805 dbus::MessageWriter writer(dbus_response.get());
806
807 patchpanel::SetVpnIntentRequest request;
808 patchpanel::SetVpnIntentResponse response;
809
810 bool success = reader.PopArrayOfBytesAsProto(&request);
811 if (!success) {
812 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
813 // Do not return yet to make sure we close the received fd.
814 }
815
816 base::ScopedFD client_socket;
817 reader.PopFileDescriptor(&client_socket);
818
819 if (success)
820 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
821
822 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900823
824 writer.AppendProtoAsArrayOfBytes(response);
825 return dbus_response;
826}
827
828std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
829 dbus::MethodCall* method_call) {
830 std::unique_ptr<dbus::Response> dbus_response(
831 dbus::Response::FromMethodCall(method_call));
832
833 dbus::MessageReader reader(method_call);
834 dbus::MessageWriter writer(dbus_response.get());
835
836 patchpanel::ConnectNamespaceRequest request;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900837
838 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900839 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
840 // Do not return yet to make sure we close the received fd and
841 // validate other arguments.
Hugo Benichi7c342672020-09-08 09:18:14 +0900842 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
843 return dbus_response;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900844 }
845
Hugo Benichicc6850f2020-01-17 13:26:06 +0900846 base::ScopedFD client_fd;
847 reader.PopFileDescriptor(&client_fd);
848 if (!client_fd.is_valid()) {
849 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
Hugo Benichi7c342672020-09-08 09:18:14 +0900850 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
851 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900852 }
853
854 pid_t pid = request.pid();
Garrick Evans263bd952020-12-03 20:27:43 +0900855 if (pid == 1 || pid == getpid()) {
856 LOG(ERROR) << "ConnectNamespaceRequest: privileged namespace pid " << pid;
857 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
858 return dbus_response;
859 }
Hugo Benichicc6850f2020-01-17 13:26:06 +0900860 {
861 ScopedNS ns(pid);
862 if (!ns.IsValid()) {
863 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900864 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
865 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900866 }
867 }
868
869 const std::string& outbound_ifname = request.outbound_physical_device();
870 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
871 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
872 << outbound_ifname;
Hugo Benichi7c342672020-09-08 09:18:14 +0900873 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
874 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900875 }
876
Hugo Benichi7c342672020-09-08 09:18:14 +0900877 auto response = ConnectNamespace(std::move(client_fd), request);
878 writer.AppendProtoAsArrayOfBytes(*response);
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900879 return dbus_response;
880}
881
Jie Jiang493cde42020-07-17 21:43:39 +0900882std::unique_ptr<dbus::Response> Manager::OnGetTrafficCounters(
883 dbus::MethodCall* method_call) {
884 std::unique_ptr<dbus::Response> dbus_response(
885 dbus::Response::FromMethodCall(method_call));
886
887 dbus::MessageReader reader(method_call);
888 dbus::MessageWriter writer(dbus_response.get());
889
890 patchpanel::TrafficCountersRequest request;
891 patchpanel::TrafficCountersResponse response;
892
893 if (!reader.PopArrayOfBytesAsProto(&request)) {
894 LOG(ERROR) << "Unable to parse TrafficCountersRequest";
895 writer.AppendProtoAsArrayOfBytes(response);
896 return dbus_response;
897 }
898
899 const std::set<std::string> devices{request.devices().begin(),
900 request.devices().end()};
Hugo Benichi1df64172020-12-13 22:59:01 +0900901 // TODO(b/175364240) Find why iptables -L -x -v -w can freeze on
902 // writing to stdout and in turn block patchpanel.
903 /*
Jie Jiang493cde42020-07-17 21:43:39 +0900904 const auto counters = counters_svc_->GetCounters(devices);
905 for (const auto& kv : counters) {
906 auto* traffic_counter = response.add_counters();
907 const auto& source_and_device = kv.first;
908 const auto& counter = kv.second;
909 traffic_counter->set_source(source_and_device.first);
910 traffic_counter->set_device(source_and_device.second);
911 traffic_counter->set_rx_bytes(counter.rx_bytes);
912 traffic_counter->set_rx_packets(counter.rx_packets);
913 traffic_counter->set_tx_bytes(counter.tx_bytes);
914 traffic_counter->set_tx_packets(counter.tx_packets);
915 }
Hugo Benichi1df64172020-12-13 22:59:01 +0900916 */
Jie Jiang493cde42020-07-17 21:43:39 +0900917
918 writer.AppendProtoAsArrayOfBytes(response);
919 return dbus_response;
920}
921
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900922std::unique_ptr<dbus::Response> Manager::OnModifyPortRule(
923 dbus::MethodCall* method_call) {
924 std::unique_ptr<dbus::Response> dbus_response(
925 dbus::Response::FromMethodCall(method_call));
926
927 dbus::MessageReader reader(method_call);
928 dbus::MessageWriter writer(dbus_response.get());
929
930 patchpanel::ModifyPortRuleRequest request;
931 patchpanel::ModifyPortRuleResponse response;
932
933 if (!reader.PopArrayOfBytesAsProto(&request)) {
934 LOG(ERROR) << "Unable to parse ModifyPortRequest";
935 writer.AppendProtoAsArrayOfBytes(response);
936 return dbus_response;
937 }
938
Jason Jeremy Imanc28df852020-07-11 17:38:26 +0900939 response.set_success(ModifyPortRule(request));
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900940 writer.AppendProtoAsArrayOfBytes(response);
941 return dbus_response;
942}
943
Jie Jiang25c1b972020-11-12 15:42:53 +0900944void Manager::OnNeighborReachabilityEvent(
Jie Jiang84966852020-09-18 18:49:05 +0900945 int ifindex,
946 const shill::IPAddress& ip_addr,
947 NeighborLinkMonitor::NeighborRole role,
Jie Jiang25c1b972020-11-12 15:42:53 +0900948 NeighborReachabilityEventSignal::EventType event_type) {
Jie Jiang84966852020-09-18 18:49:05 +0900949 if (!ip_addr.IsValid()) {
950 LOG(DFATAL) << "ip_addr is not valid";
951 return;
952 }
953
Jie Jiang25c1b972020-11-12 15:42:53 +0900954 using SignalProto = NeighborReachabilityEventSignal;
Jie Jiang84966852020-09-18 18:49:05 +0900955 SignalProto proto;
956 proto.set_ifindex(ifindex);
957 proto.set_ip_addr(ip_addr.ToString());
Jie Jiang25c1b972020-11-12 15:42:53 +0900958 proto.set_type(event_type);
Jie Jiang84966852020-09-18 18:49:05 +0900959 switch (role) {
960 case NeighborLinkMonitor::NeighborRole::kGateway:
961 proto.set_role(SignalProto::GATEWAY);
962 break;
963 case NeighborLinkMonitor::NeighborRole::kDNSServer:
964 proto.set_role(SignalProto::DNS_SERVER);
965 break;
966 case NeighborLinkMonitor::NeighborRole::kGatewayAndDNSServer:
967 proto.set_role(SignalProto::GATEWAY_AND_DNS_SERVER);
968 break;
969 default:
970 NOTREACHED();
971 }
972
Jie Jiang25c1b972020-11-12 15:42:53 +0900973 dbus::Signal signal(kPatchPanelInterface, kNeighborReachabilityEventSignal);
Jie Jiang84966852020-09-18 18:49:05 +0900974 dbus::MessageWriter writer(&signal);
975 if (!writer.AppendProtoAsArrayOfBytes(proto)) {
Jie Jiang25c1b972020-11-12 15:42:53 +0900976 LOG(ERROR) << "Failed to encode proto NeighborReachabilityEventSignal";
Jie Jiang84966852020-09-18 18:49:05 +0900977 return;
978 }
979
980 dbus_svc_path_->SendSignal(&signal);
981}
982
Hugo Benichi7c342672020-09-08 09:18:14 +0900983std::unique_ptr<patchpanel::ConnectNamespaceResponse> Manager::ConnectNamespace(
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900984 base::ScopedFD client_fd,
Hugo Benichi7c342672020-09-08 09:18:14 +0900985 const patchpanel::ConnectNamespaceRequest& request) {
986 auto response = std::make_unique<patchpanel::ConnectNamespaceResponse>();
987
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900988 std::unique_ptr<Subnet> subnet =
989 addr_mgr_.AllocateIPv4Subnet(AddressManager::Guest::MINIJAIL_NETNS);
990 if (!subnet) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900991 LOG(ERROR) << "ConnectNamespace: exhausted IPv4 subnet space";
992 return response;
Hugo Benichie8758b52020-04-03 14:49:01 +0900993 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900994
Hugo Benichi7352ad92020-04-07 16:11:59 +0900995 // Dup the client fd into our own: this guarantees that the fd number will
996 // be stable and tied to the actual kernel resources used by the client.
997 base::ScopedFD local_client_fd(dup(client_fd.get()));
998 if (!local_client_fd.is_valid()) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900999 PLOG(ERROR) << "ConnectNamespace: failed to dup() client fd";
1000 return response;
Hugo Benichi7352ad92020-04-07 16:11:59 +09001001 }
1002
Hugo Benichi7c342672020-09-08 09:18:14 +09001003 // Add the duped fd to the epoll watcher.
Hugo Benichi7352ad92020-04-07 16:11:59 +09001004 // TODO(hugobenichi) Find a way to reuse base::FileDescriptorWatcher for
1005 // listening to EPOLLHUP.
1006 struct epoll_event epevent;
1007 epevent.events = EPOLLIN; // EPOLLERR | EPOLLHUP are always waited for.
1008 epevent.data.fd = local_client_fd.get();
1009 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_ADD,
1010 local_client_fd.get(), &epevent) != 0) {
Hugo Benichi7c342672020-09-08 09:18:14 +09001011 PLOG(ERROR) << "ConnectNamespace: epoll_ctl(EPOLL_CTL_ADD) failed";
1012 return response;
Hugo Benichi7352ad92020-04-07 16:11:59 +09001013 }
1014
Hugo Benichi7c342672020-09-08 09:18:14 +09001015 const std::string ifname_id = std::to_string(connected_namespaces_next_id_);
Hugo Benichifcf81022020-12-04 11:01:37 +09001016 ConnectedNamespace nsinfo = {};
1017 nsinfo.pid = request.pid();
1018 nsinfo.netns_name = "connected_netns_" + ifname_id;
Hugo Benichi93306e52020-12-04 16:08:00 +09001019 nsinfo.source = ProtoToTrafficSource(request.traffic_source());
1020 if (nsinfo.source == TrafficSource::UNKNOWN)
1021 nsinfo.source = TrafficSource::SYSTEM;
Hugo Benichifcf81022020-12-04 11:01:37 +09001022 nsinfo.outbound_ifname = request.outbound_physical_device();
Hugo Benichi93306e52020-12-04 16:08:00 +09001023 nsinfo.route_on_vpn = request.route_on_vpn();
Hugo Benichifcf81022020-12-04 11:01:37 +09001024 nsinfo.host_ifname = "arc_ns" + ifname_id;
1025 nsinfo.peer_ifname = "veth" + ifname_id;
1026 nsinfo.peer_subnet = std::move(subnet);
1027 nsinfo.peer_mac_addr = addr_mgr_.GenerateMacAddress();
1028
1029 if (!datapath_->StartRoutingNamespace(nsinfo)) {
Hugo Benichi7c342672020-09-08 09:18:14 +09001030 LOG(ERROR) << "ConnectNamespace: failed to setup datapath";
1031 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL,
1032 local_client_fd.get(), nullptr) != 0)
1033 PLOG(ERROR) << "ConnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
1034 return response;
1035 }
1036
Hugo Benichifcf81022020-12-04 11:01:37 +09001037 // Prepare the response before storing ConnectedNamespace.
1038 response->set_peer_ifname(nsinfo.peer_ifname);
1039 response->set_peer_ipv4_address(nsinfo.peer_subnet->AddressAtOffset(1));
1040 response->set_host_ifname(nsinfo.host_ifname);
1041 response->set_host_ipv4_address(nsinfo.peer_subnet->AddressAtOffset(0));
Hugo Benichi7c342672020-09-08 09:18:14 +09001042 auto* response_subnet = response->mutable_ipv4_subnet();
Hugo Benichifcf81022020-12-04 11:01:37 +09001043 response_subnet->set_base_addr(nsinfo.peer_subnet->BaseAddress());
1044 response_subnet->set_prefix_len(nsinfo.peer_subnet->PrefixLength());
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001045
Hugo Benichifcf81022020-12-04 11:01:37 +09001046 LOG(INFO) << "Connected network namespace " << nsinfo;
1047
1048 // Store ConnectedNamespace
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001049 connected_namespaces_next_id_++;
Hugo Benichi7352ad92020-04-07 16:11:59 +09001050 int fdkey = local_client_fd.release();
Hugo Benichifcf81022020-12-04 11:01:37 +09001051 connected_namespaces_.insert(std::make_pair(fdkey, std::move(nsinfo)));
Hugo Benichi7352ad92020-04-07 16:11:59 +09001052
1053 if (connected_namespaces_.size() == 1) {
1054 LOG(INFO) << "Starting ConnectNamespace client fds monitoring";
1055 CheckConnectedNamespaces();
1056 }
Hugo Benichi7c342672020-09-08 09:18:14 +09001057
1058 return response;
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001059}
1060
1061void Manager::DisconnectNamespace(int client_fd) {
1062 auto it = connected_namespaces_.find(client_fd);
1063 if (it == connected_namespaces_.end()) {
Hugo Benichifcf81022020-12-04 11:01:37 +09001064 LOG(ERROR) << "No ConnectedNamespace found for client_fd " << client_fd;
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001065 return;
1066 }
1067
Hugo Benichi7352ad92020-04-07 16:11:59 +09001068 // Remove the client fd dupe from the epoll watcher and close it.
1069 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL, client_fd,
Hugo Benichie8758b52020-04-03 14:49:01 +09001070 nullptr) != 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +09001071 PLOG(ERROR) << "DisconnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +09001072 if (close(client_fd) < 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +09001073 PLOG(ERROR) << "DisconnectNamespace: close(client_fd) failed";
Hugo Benichi7352ad92020-04-07 16:11:59 +09001074
Hugo Benichifcf81022020-12-04 11:01:37 +09001075 datapath_->StopRoutingNamespace(it->second);
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001076 LOG(INFO) << "Disconnected network namespace " << it->second;
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001077 // This release the allocated IPv4 subnet.
1078 connected_namespaces_.erase(it);
1079}
1080
Hugo Benichi7352ad92020-04-07 16:11:59 +09001081// TODO(hugobenichi) Generalize this check to all resources created by
1082// patchpanel on behalf of a remote client.
1083void Manager::CheckConnectedNamespaces() {
1084 int max_event = 10;
1085 struct epoll_event epevents[max_event];
1086 int nready = epoll_wait(connected_namespaces_epollfd_, epevents, max_event,
1087 0 /* do not block */);
1088 if (nready < 0)
1089 PLOG(ERROR) << "CheckConnectedNamespaces: epoll_wait(0) failed";
1090
1091 for (int i = 0; i < nready; i++)
1092 if (epevents[i].events & (EPOLLHUP | EPOLLERR))
1093 DisconnectNamespace(epevents[i].data.fd);
1094
1095 if (connected_namespaces_.empty()) {
1096 LOG(INFO) << "Stopping ConnectNamespace client fds monitoring";
1097 return;
1098 }
1099
Qijiang Fan2d7aeb42020-05-19 02:06:39 +09001100 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Hugo Benichi7352ad92020-04-07 16:11:59 +09001101 FROM_HERE,
1102 base::Bind(&Manager::CheckConnectedNamespaces,
Hugo Benichie8758b52020-04-03 14:49:01 +09001103 weak_factory_.GetWeakPtr()),
Hugo Benichi7352ad92020-04-07 16:11:59 +09001104 kConnectNamespaceCheckInterval);
1105}
1106
Jason Jeremy Imanc28df852020-07-11 17:38:26 +09001107bool Manager::ModifyPortRule(const patchpanel::ModifyPortRuleRequest& request) {
1108 switch (request.proto()) {
1109 case patchpanel::ModifyPortRuleRequest::TCP:
1110 case patchpanel::ModifyPortRuleRequest::UDP:
1111 break;
1112 default:
1113 LOG(ERROR) << "Unknown protocol " << request.proto();
1114 return false;
1115 }
1116
1117 switch (request.op()) {
1118 case patchpanel::ModifyPortRuleRequest::CREATE:
1119 switch (request.type()) {
1120 case patchpanel::ModifyPortRuleRequest::ACCESS:
1121 return firewall_.AddAcceptRules(request.proto(),
1122 request.input_dst_port(),
1123 request.input_ifname());
1124 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
1125 return firewall_.AddLoopbackLockdownRules(request.proto(),
1126 request.input_dst_port());
1127 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1128 return firewall_.AddIpv4ForwardRule(
1129 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1130 request.input_ifname(), request.dst_ip(), request.dst_port());
1131 default:
1132 LOG(ERROR) << "Unknown port rule type " << request.type();
1133 return false;
1134 }
1135 case patchpanel::ModifyPortRuleRequest::DELETE:
1136 switch (request.type()) {
1137 case patchpanel::ModifyPortRuleRequest::ACCESS:
1138 return firewall_.DeleteAcceptRules(request.proto(),
1139 request.input_dst_port(),
1140 request.input_ifname());
1141 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
1142 return firewall_.DeleteLoopbackLockdownRules(
1143 request.proto(), request.input_dst_port());
1144 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1145 return firewall_.DeleteIpv4ForwardRule(
1146 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1147 request.input_ifname(), request.dst_ip(), request.dst_port());
1148 default:
1149 LOG(ERROR) << "Unknown port rule type " << request.type();
1150 return false;
1151 }
1152 default:
1153 LOG(ERROR) << "Unknown operation " << request.op();
1154 return false;
1155 }
1156}
1157
Garrick Evanse94a14e2019-11-11 10:32:13 +09001158void Manager::SendGuestMessage(const GuestMessage& msg) {
Garrick Evans96e03042019-05-28 14:30:52 +09001159 IpHelperMessage ipm;
1160 *ipm.mutable_guest_message() = msg;
Garrick Evans96e03042019-05-28 14:30:52 +09001161 adb_proxy_->SendMessage(ipm);
Garrick Evanse94a14e2019-11-11 10:32:13 +09001162 mcast_proxy_->SendMessage(ipm);
1163 nd_proxy_->SendMessage(ipm);
Garrick Evans96e03042019-05-28 14:30:52 +09001164}
1165
Garrick Evans4ac09852020-01-16 14:09:22 +09001166void Manager::StartForwarding(const std::string& ifname_physical,
1167 const std::string& ifname_virtual,
Garrick Evans4ac09852020-01-16 14:09:22 +09001168 bool ipv6,
1169 bool multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001170 if (ifname_physical.empty() || ifname_virtual.empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001171 return;
1172
1173 IpHelperMessage ipm;
1174 DeviceMessage* msg = ipm.mutable_device_message();
1175 msg->set_dev_ifname(ifname_physical);
Garrick Evans4ac09852020-01-16 14:09:22 +09001176 msg->set_br_ifname(ifname_virtual);
1177
1178 if (ipv6) {
1179 LOG(INFO) << "Starting IPv6 forwarding from " << ifname_physical << " to "
1180 << ifname_virtual;
1181
1182 if (!datapath_->AddIPv6Forwarding(ifname_physical, ifname_virtual)) {
1183 LOG(ERROR) << "Failed to setup iptables forwarding rule for IPv6 from "
1184 << ifname_physical << " to " << ifname_virtual;
1185 }
1186 if (!datapath_->MaskInterfaceFlags(ifname_physical, IFF_ALLMULTI)) {
1187 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1188 << ifname_physical;
1189 }
1190 if (!datapath_->MaskInterfaceFlags(ifname_virtual, IFF_ALLMULTI)) {
1191 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1192 << ifname_virtual;
1193 }
1194 nd_proxy_->SendMessage(ipm);
1195 }
1196
1197 if (multicast) {
1198 LOG(INFO) << "Starting multicast forwarding from " << ifname_physical
1199 << " to " << ifname_virtual;
1200 mcast_proxy_->SendMessage(ipm);
1201 }
1202}
1203
1204void Manager::StopForwarding(const std::string& ifname_physical,
1205 const std::string& ifname_virtual,
1206 bool ipv6,
1207 bool multicast) {
1208 if (ifname_physical.empty())
1209 return;
1210
1211 IpHelperMessage ipm;
1212 DeviceMessage* msg = ipm.mutable_device_message();
1213 msg->set_dev_ifname(ifname_physical);
1214 msg->set_teardown(true);
Taoyu Li7dca19a2020-03-16 16:27:07 +09001215 if (!ifname_virtual.empty()) {
1216 msg->set_br_ifname(ifname_virtual);
1217 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001218
1219 if (ipv6) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001220 if (ifname_virtual.empty()) {
1221 LOG(INFO) << "Stopping IPv6 forwarding on " << ifname_physical;
1222 } else {
1223 LOG(INFO) << "Stopping IPv6 forwarding from " << ifname_physical << " to "
1224 << ifname_virtual;
1225 datapath_->RemoveIPv6Forwarding(ifname_physical, ifname_virtual);
1226 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001227 nd_proxy_->SendMessage(ipm);
1228 }
1229
1230 if (multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001231 if (ifname_virtual.empty()) {
1232 LOG(INFO) << "Stopping multicast forwarding on " << ifname_physical;
1233 } else {
1234 LOG(INFO) << "Stopping multicast forwarding from " << ifname_physical
1235 << " to " << ifname_virtual;
1236 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001237 mcast_proxy_->SendMessage(ipm);
1238 }
1239}
1240
Taoyu Lia0727dc2020-09-24 19:54:59 +09001241void Manager::OnNDProxyMessage(const NDProxyMessage& msg) {
1242 LOG_IF(DFATAL, msg.ifname().empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001243 << "Received DeviceMessage w/ empty dev_ifname";
Taoyu Lia0727dc2020-09-24 19:54:59 +09001244 switch (msg.type()) {
1245 case NDProxyMessage::ADD_ROUTE:
1246 if (!datapath_->AddIPv6HostRoute(msg.ifname(), msg.ip6addr(), 128)) {
1247 LOG(WARNING) << "Failed to setup the IPv6 route for interface "
1248 << msg.ifname() << ", addr " << msg.ip6addr();
1249 }
1250 break;
1251 case NDProxyMessage::ADD_ADDR:
1252 if (!datapath_->AddIPv6Address(msg.ifname(), msg.ip6addr())) {
1253 LOG(WARNING) << "Failed to setup the IPv6 address for interface "
1254 << msg.ifname() << ", addr " << msg.ip6addr();
1255 }
1256 break;
1257 case NDProxyMessage::DEL_ADDR:
1258 datapath_->RemoveIPv6Address(msg.ifname(), msg.ip6addr());
1259 break;
1260 default:
1261 LOG(ERROR) << "Unknown NDProxy event " << msg.type();
1262 NOTREACHED();
Garrick Evans4ac09852020-01-16 14:09:22 +09001263 }
1264}
1265
Garrick Evans3388a032020-03-24 11:25:55 +09001266} // namespace patchpanel