blob: 2a3b08dac72d468b0cf09bd49ecbe7001fcbd640 [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
Garrick Evans207e7482019-12-16 11:54:36 +090070Manager::~Manager() {
71 OnShutdown(nullptr);
72}
73
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +090074std::map<const std::string, bool> Manager::cached_feature_enabled_ = {};
75
76bool Manager::ShouldEnableFeature(
77 int min_android_sdk_version,
78 int min_chrome_milestone,
79 const std::vector<std::string>& supported_boards,
80 const std::string& feature_name) {
81 static const char kLsbReleasePath[] = "/etc/lsb-release";
82
83 const auto& cached_result = cached_feature_enabled_.find(feature_name);
84 if (cached_result != cached_feature_enabled_.end())
85 return cached_result->second;
86
87 auto check = [min_android_sdk_version, min_chrome_milestone,
88 &supported_boards, &feature_name]() {
89 brillo::KeyValueStore store;
90 if (!store.Load(base::FilePath(kLsbReleasePath))) {
91 LOG(ERROR) << "Could not read lsb-release";
92 return false;
93 }
94
95 std::string value;
96 if (!store.GetString("CHROMEOS_ARC_ANDROID_SDK_VERSION", &value)) {
97 LOG(ERROR) << feature_name
98 << " disabled - cannot determine Android SDK version";
99 return false;
100 }
101 int ver = 0;
102 if (!base::StringToInt(value.c_str(), &ver)) {
103 LOG(ERROR) << feature_name << " disabled - invalid Android SDK version";
104 return false;
105 }
106 if (ver < min_android_sdk_version) {
107 LOG(INFO) << feature_name << " disabled for Android SDK " << value;
108 return false;
109 }
110
111 if (!store.GetString("CHROMEOS_RELEASE_CHROME_MILESTONE", &value)) {
112 LOG(ERROR) << feature_name
113 << " disabled - cannot determine ChromeOS milestone";
114 return false;
115 }
116 if (!base::StringToInt(value.c_str(), &ver)) {
117 LOG(ERROR) << feature_name << " disabled - invalid ChromeOS milestone";
118 return false;
119 }
120 if (ver < min_chrome_milestone) {
121 LOG(INFO) << feature_name << " disabled for ChromeOS milestone " << value;
122 return false;
123 }
124
125 if (!store.GetString("CHROMEOS_RELEASE_BOARD", &value)) {
126 LOG(ERROR) << feature_name << " disabled - cannot determine board";
127 return false;
128 }
129 if (!supported_boards.empty() &&
130 std::find(supported_boards.begin(), supported_boards.end(), value) ==
131 supported_boards.end()) {
132 LOG(INFO) << feature_name << " disabled for board " << value;
133 return false;
134 }
135 return true;
136 };
137
138 bool result = check();
139 cached_feature_enabled_.emplace(feature_name, result);
140 return result;
141}
142
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700143int Manager::OnInit() {
Garrick Evans54861622019-07-19 09:05:09 +0900144 prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800145
146 // Handle subprocess lifecycle.
147 process_reaper_.Register(this);
Hugo Benichi935eca92018-07-03 13:47:24 +0900148
149 CHECK(process_reaper_.WatchForChild(
Garrick Evans96e03042019-05-28 14:30:52 +0900150 FROM_HERE, adb_proxy_->pid(),
151 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
152 adb_proxy_->pid())))
153 << "Failed to watch adb-proxy child process";
Taoyu Liaf944c92019-10-01 12:22:31 +0900154 CHECK(process_reaper_.WatchForChild(
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900155 FROM_HERE, mcast_proxy_->pid(),
156 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
157 nd_proxy_->pid())))
158 << "Failed to watch multicast-proxy child process";
159 CHECK(process_reaper_.WatchForChild(
Taoyu Liaf944c92019-10-01 12:22:31 +0900160 FROM_HERE, nd_proxy_->pid(),
161 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
162 nd_proxy_->pid())))
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900163 << "Failed to watch nd-proxy child process";
Garrick Evans96e03042019-05-28 14:30:52 +0900164
Garrick Evans49879532018-12-03 13:15:36 +0900165 // Run after Daemon::OnInit().
hschamf9546312020-04-14 15:12:40 +0900166 base::ThreadTaskRunnerHandle::Get()->PostTask(
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700167 FROM_HERE,
168 base::Bind(&Manager::InitialSetup, weak_factory_.GetWeakPtr()));
169
170 return DBusDaemon::OnInit();
171}
172
173void Manager::InitialSetup() {
Garrick Evans08843932019-09-17 14:41:08 +0900174 LOG(INFO) << "Setting up DBus service interface";
175 dbus_svc_path_ = bus_->GetExportedObject(
176 dbus::ObjectPath(patchpanel::kPatchPanelServicePath));
177 if (!dbus_svc_path_) {
178 LOG(FATAL) << "Failed to export " << patchpanel::kPatchPanelServicePath
179 << " object";
180 }
181
Hugo Benichi76be34a2020-08-26 22:35:54 +0900182 shill_client_ = std::make_unique<ShillClient>(bus_);
183
Garrick Evans08843932019-09-17 14:41:08 +0900184 using ServiceMethod =
185 std::unique_ptr<dbus::Response> (Manager::*)(dbus::MethodCall*);
186 const std::map<const char*, ServiceMethod> kServiceMethods = {
187 {patchpanel::kArcStartupMethod, &Manager::OnArcStartup},
188 {patchpanel::kArcShutdownMethod, &Manager::OnArcShutdown},
189 {patchpanel::kArcVmStartupMethod, &Manager::OnArcVmStartup},
190 {patchpanel::kArcVmShutdownMethod, &Manager::OnArcVmShutdown},
Garrick Evans47c19272019-11-21 10:58:21 +0900191 {patchpanel::kTerminaVmStartupMethod, &Manager::OnTerminaVmStartup},
192 {patchpanel::kTerminaVmShutdownMethod, &Manager::OnTerminaVmShutdown},
Garrick Evans51d5b552020-01-30 10:42:06 +0900193 {patchpanel::kPluginVmStartupMethod, &Manager::OnPluginVmStartup},
194 {patchpanel::kPluginVmShutdownMethod, &Manager::OnPluginVmShutdown},
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900195 {patchpanel::kSetVpnIntentMethod, &Manager::OnSetVpnIntent},
Hugo Benichib56b77c2020-01-15 16:00:56 +0900196 {patchpanel::kConnectNamespaceMethod, &Manager::OnConnectNamespace},
Jie Jiang493cde42020-07-17 21:43:39 +0900197 {patchpanel::kGetTrafficCountersMethod, &Manager::OnGetTrafficCounters},
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900198 {patchpanel::kModifyPortRuleMethod, &Manager::OnModifyPortRule},
Garrick Evans02e6e872020-11-30 11:53:13 +0900199 {patchpanel::kGetDevicesMethod, &Manager::OnGetDevices},
Garrick Evans08843932019-09-17 14:41:08 +0900200 };
201
202 for (const auto& kv : kServiceMethods) {
203 if (!dbus_svc_path_->ExportMethodAndBlock(
204 patchpanel::kPatchPanelInterface, kv.first,
205 base::Bind(&HandleSynchronousDBusMethodCall,
206 base::Bind(kv.second, base::Unretained(this))))) {
207 LOG(FATAL) << "Failed to export method " << kv.first;
208 }
209 }
210
211 if (!bus_->RequestOwnershipAndBlock(patchpanel::kPatchPanelServiceName,
212 dbus::Bus::REQUIRE_PRIMARY)) {
213 LOG(FATAL) << "Failed to take ownership of "
214 << patchpanel::kPatchPanelServiceName;
215 }
216 LOG(INFO) << "DBus service interface ready";
217
Hugo Benichifda77232020-08-21 18:28:15 +0900218 routing_svc_ = std::make_unique<RoutingService>();
Hugo Benichi058a26a2020-11-26 10:10:39 +0900219 counters_svc_ =
220 std::make_unique<CountersService>(datapath_.get(), runner_.get());
Hugo Benichifda77232020-08-21 18:28:15 +0900221
Hugo Benichibf811c62020-09-07 17:30:45 +0900222 // b/162966185: Allow Jetstream to disable:
223 // - the IP forwarding setup used for hosting VMs and containers,
224 // - the iptables rules for fwmark based routing.
225 if (!USE_JETSTREAM_ROUTING) {
226 datapath_->Start();
Hugo Benichi2a940542020-10-26 18:50:49 +0900227 shill_client_->RegisterDefaultDeviceChangedHandler(base::BindRepeating(
228 &Manager::OnDefaultDeviceChanged, weak_factory_.GetWeakPtr()));
Hugo Benichibf811c62020-09-07 17:30:45 +0900229 shill_client_->RegisterDevicesChangedHandler(base::BindRepeating(
230 &Manager::OnDevicesChanged, weak_factory_.GetWeakPtr()));
231 }
Hugo Benichifda77232020-08-21 18:28:15 +0900232
Taoyu Lia0727dc2020-09-24 19:54:59 +0900233 nd_proxy_->RegisterNDProxyMessageHandler(
234 base::Bind(&Manager::OnNDProxyMessage, weak_factory_.GetWeakPtr()));
Hugo Benichifda77232020-08-21 18:28:15 +0900235
Hugo Benichifda77232020-08-21 18:28:15 +0900236 auto* const forwarder = static_cast<TrafficForwarder*>(this);
237
238 GuestMessage::GuestType arc_guest =
239 USE_ARCVM ? GuestMessage::ARC_VM : GuestMessage::ARC;
Garrick Evans209a80a2020-11-30 14:42:40 +0900240 arc_svc_ = std::make_unique<ArcService>(
241 shill_client_.get(), datapath_.get(), &addr_mgr_, forwarder, arc_guest,
242 base::BindRepeating(&Manager::OnDeviceChanged,
243 weak_factory_.GetWeakPtr()));
244 cros_svc_ = std::make_unique<CrostiniService>(
245 shill_client_.get(), &addr_mgr_, datapath_.get(), forwarder,
246 base::BindRepeating(&Manager::OnDeviceChanged,
247 weak_factory_.GetWeakPtr()));
Jie Jiang84966852020-09-18 18:49:05 +0900248 network_monitor_svc_ = std::make_unique<NetworkMonitorService>(
249 shill_client_.get(),
Jie Jiang25c1b972020-11-12 15:42:53 +0900250 base::BindRepeating(&Manager::OnNeighborReachabilityEvent,
Jie Jiang84966852020-09-18 18:49:05 +0900251 weak_factory_.GetWeakPtr()));
Hugo Benichifda77232020-08-21 18:28:15 +0900252 network_monitor_svc_->Start();
Hugo Benichi058a26a2020-11-26 10:10:39 +0900253 counters_svc_->Init(shill_client_->get_devices());
Hugo Benichifda77232020-08-21 18:28:15 +0900254 nd_proxy_->Listen();
255}
256
257void Manager::OnShutdown(int* exit_code) {
258 LOG(INFO) << "Shutting down and cleaning up";
Jie Jiang84966852020-09-18 18:49:05 +0900259 network_monitor_svc_.reset();
Hugo Benichifda77232020-08-21 18:28:15 +0900260 cros_svc_.reset();
261 arc_svc_.reset();
262 close(connected_namespaces_epollfd_);
263 // Tear down any remaining connected namespace.
264 std::vector<int> connected_namespaces_fdkeys;
265 for (const auto& kv : connected_namespaces_)
266 connected_namespaces_fdkeys.push_back(kv.first);
267 for (const int fdkey : connected_namespaces_fdkeys)
268 DisconnectNamespace(fdkey);
Hugo Benichibf811c62020-09-07 17:30:45 +0900269 if (!USE_JETSTREAM_ROUTING)
270 datapath_->Stop();
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 Benichi058a26a2020-11-26 10:10:39 +0900330 counters_svc_->OnPhysicalDeviceRemoved(ifname);
331 }
Hugo Benichi76be34a2020-08-26 22:35:54 +0900332
Hugo Benichi058a26a2020-11-26 10:10:39 +0900333 for (const std::string& ifname : added) {
Hugo Benichi76be34a2020-08-26 22:35:54 +0900334 datapath_->StartConnectionPinning(ifname);
Hugo Benichi058a26a2020-11-26 10:10:39 +0900335 counters_svc_->OnPhysicalDeviceAdded(ifname);
336 }
Hugo Benichi76be34a2020-08-26 22:35:54 +0900337}
338
Garrick Evans209a80a2020-11-30 14:42:40 +0900339void Manager::OnDeviceChanged(const Device& device,
340 Device::ChangeEvent event,
341 GuestMessage::GuestType guest_type) {
342 dbus::Signal signal(kPatchPanelInterface, kNetworkDeviceChangedSignal);
343 NetworkDeviceChangedSignal proto;
344 proto.set_event(event == Device::ChangeEvent::ADDED
345 ? NetworkDeviceChangedSignal::DEVICE_ADDED
346 : NetworkDeviceChangedSignal::DEVICE_REMOVED);
347 auto* dev = proto.mutable_device();
348 dev->set_ifname(device.host_ifname());
349 dev->set_ipv4_addr(device.config().guest_ipv4_addr());
350 if (const auto* subnet = device.config().ipv4_subnet()) {
351 auto* sub = dev->mutable_ipv4_subnet();
352 sub->set_base_addr(subnet->BaseAddress());
353 sub->set_prefix_len(subnet->PrefixLength());
354 }
355 switch (guest_type) {
356 case GuestMessage::ARC:
357 dev->set_guest_type(NetworkDevice::ARC);
358 break;
359 case GuestMessage::ARC_VM:
360 dev->set_guest_type(NetworkDevice::ARCVM);
361 break;
362 case GuestMessage::TERMINA_VM:
363 dev->set_guest_type(NetworkDevice::TERMINA_VM);
364 break;
365 case GuestMessage::PLUGIN_VM:
366 dev->set_guest_type(NetworkDevice::PLUGIN_VM);
367 break;
368 default:
369 LOG(ERROR) << "Unknown device type";
370 }
371
372 dbus::MessageWriter(&signal).AppendProtoAsArrayOfBytes(proto);
373 dbus_svc_path_->SendSignal(&signal);
374}
375
Garrick Evanse94a14e2019-11-11 10:32:13 +0900376bool Manager::StartArc(pid_t pid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900377 if (!arc_svc_->Start(pid))
378 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900379
380 GuestMessage msg;
381 msg.set_event(GuestMessage::START);
382 msg.set_type(GuestMessage::ARC);
383 msg.set_arc_pid(pid);
384 SendGuestMessage(msg);
385
386 return true;
387}
388
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900389void Manager::StopArc() {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900390 GuestMessage msg;
391 msg.set_event(GuestMessage::STOP);
392 msg.set_type(GuestMessage::ARC);
393 SendGuestMessage(msg);
394
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900395 // After the ARC container has stopped, the pid is not known anymore.
396 // The pid argument is ignored by ArcService.
397 arc_svc_->Stop(0);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900398}
399
Garrick Evans015b0d62020-02-07 09:06:38 +0900400bool Manager::StartArcVm(uint32_t cid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900401 if (!arc_svc_->Start(cid))
402 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900403
404 GuestMessage msg;
405 msg.set_event(GuestMessage::START);
406 msg.set_type(GuestMessage::ARC_VM);
407 msg.set_arcvm_vsock_cid(cid);
408 SendGuestMessage(msg);
409
410 return true;
411}
412
Garrick Evans015b0d62020-02-07 09:06:38 +0900413void Manager::StopArcVm(uint32_t cid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900414 GuestMessage msg;
415 msg.set_event(GuestMessage::STOP);
416 msg.set_type(GuestMessage::ARC_VM);
417 SendGuestMessage(msg);
418
Garrick Evans21173b12019-11-20 15:23:16 +0900419 arc_svc_->Stop(cid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900420}
421
Garrick Evans51d5b552020-01-30 10:42:06 +0900422bool Manager::StartCrosVm(uint64_t vm_id,
423 GuestMessage::GuestType vm_type,
Garrick Evans53a2a982020-02-05 10:53:35 +0900424 uint32_t subnet_index) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900425 DCHECK(vm_type == GuestMessage::TERMINA_VM ||
426 vm_type == GuestMessage::PLUGIN_VM);
427
428 if (!cros_svc_->Start(vm_id, vm_type == GuestMessage::TERMINA_VM,
429 subnet_index))
Garrick Evans47c19272019-11-21 10:58:21 +0900430 return false;
431
432 GuestMessage msg;
433 msg.set_event(GuestMessage::START);
Garrick Evans51d5b552020-01-30 10:42:06 +0900434 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900435 SendGuestMessage(msg);
436
437 return true;
438}
439
Garrick Evans51d5b552020-01-30 10:42:06 +0900440void Manager::StopCrosVm(uint64_t vm_id, GuestMessage::GuestType vm_type) {
Garrick Evans47c19272019-11-21 10:58:21 +0900441 GuestMessage msg;
442 msg.set_event(GuestMessage::STOP);
Garrick Evans51d5b552020-01-30 10:42:06 +0900443 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900444 SendGuestMessage(msg);
445
Garrick Evans51d5b552020-01-30 10:42:06 +0900446 cros_svc_->Stop(vm_id, vm_type == GuestMessage::TERMINA_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900447}
448
Garrick Evans02e6e872020-11-30 11:53:13 +0900449std::unique_ptr<dbus::Response> Manager::OnGetDevices(
450 dbus::MethodCall* method_call) {
451 std::unique_ptr<dbus::Response> dbus_response(
452 dbus::Response::FromMethodCall(method_call));
453
454 dbus::MessageReader reader(method_call);
455 dbus::MessageWriter writer(dbus_response.get());
456
457 patchpanel::GetDevicesRequest request;
458 patchpanel::GetDevicesResponse response;
459
460 if (!reader.PopArrayOfBytesAsProto(&request)) {
461 LOG(ERROR) << "Unable to parse request";
462 writer.AppendProtoAsArrayOfBytes(response);
463 return dbus_response;
464 }
465
466 static const auto arc_guest_type =
467 USE_ARCVM ? NetworkDevice::ARCVM : NetworkDevice::ARC;
468
469 arc_svc_->ScanDevices(base::BindRepeating(
470 [](patchpanel::GetDevicesResponse* resp, const Device& device) {
471 auto* dev = resp->add_devices();
472 dev->set_ifname(device.host_ifname());
473 dev->set_ipv4_addr(device.config().guest_ipv4_addr());
474 dev->set_guest_type(arc_guest_type);
475 if (const auto* subnet = device.config().ipv4_subnet()) {
476 auto* sub = dev->mutable_ipv4_subnet();
477 sub->set_base_addr(subnet->BaseAddress());
478 sub->set_prefix_len(subnet->PrefixLength());
479 }
480 },
481 &response));
482
483 cros_svc_->ScanDevices(base::BindRepeating(
484 [](patchpanel::GetDevicesResponse* resp, uint64_t vm_id, bool is_termina,
485 const Device& device) {
486 auto* dev = resp->add_devices();
487 dev->set_ifname(device.host_ifname());
488 dev->set_ipv4_addr(device.config().guest_ipv4_addr());
489 dev->set_guest_type(is_termina ? NetworkDevice::TERMINA_VM
490 : NetworkDevice::PLUGIN_VM);
491 if (const auto* subnet = device.config().ipv4_subnet()) {
492 auto* sub = dev->mutable_ipv4_subnet();
493 sub->set_base_addr(subnet->BaseAddress());
494 sub->set_prefix_len(subnet->PrefixLength());
495 }
496 },
497 &response));
498
499 writer.AppendProtoAsArrayOfBytes(response);
500 return dbus_response;
501}
502
Garrick Evans08843932019-09-17 14:41:08 +0900503std::unique_ptr<dbus::Response> Manager::OnArcStartup(
504 dbus::MethodCall* method_call) {
505 LOG(INFO) << "ARC++ starting up";
506
507 std::unique_ptr<dbus::Response> dbus_response(
508 dbus::Response::FromMethodCall(method_call));
509
510 dbus::MessageReader reader(method_call);
511 dbus::MessageWriter writer(dbus_response.get());
512
513 patchpanel::ArcStartupRequest request;
514 patchpanel::ArcStartupResponse response;
515
516 if (!reader.PopArrayOfBytesAsProto(&request)) {
517 LOG(ERROR) << "Unable to parse request";
518 writer.AppendProtoAsArrayOfBytes(response);
519 return dbus_response;
520 }
521
Garrick Evanse01bf072019-11-15 09:08:19 +0900522 if (!StartArc(request.pid()))
523 LOG(ERROR) << "Failed to start ARC++ network service";
Garrick Evanse94a14e2019-11-11 10:32:13 +0900524
Garrick Evans08843932019-09-17 14:41:08 +0900525 writer.AppendProtoAsArrayOfBytes(response);
526 return dbus_response;
527}
528
529std::unique_ptr<dbus::Response> Manager::OnArcShutdown(
530 dbus::MethodCall* method_call) {
531 LOG(INFO) << "ARC++ shutting down";
532
533 std::unique_ptr<dbus::Response> dbus_response(
534 dbus::Response::FromMethodCall(method_call));
535
536 dbus::MessageReader reader(method_call);
537 dbus::MessageWriter writer(dbus_response.get());
538
539 patchpanel::ArcShutdownRequest request;
540 patchpanel::ArcShutdownResponse response;
541
542 if (!reader.PopArrayOfBytesAsProto(&request)) {
543 LOG(ERROR) << "Unable to parse request";
544 writer.AppendProtoAsArrayOfBytes(response);
545 return dbus_response;
546 }
547
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900548 StopArc();
Garrick Evanse94a14e2019-11-11 10:32:13 +0900549
Garrick Evans08843932019-09-17 14:41:08 +0900550 writer.AppendProtoAsArrayOfBytes(response);
551 return dbus_response;
552}
553
554std::unique_ptr<dbus::Response> Manager::OnArcVmStartup(
555 dbus::MethodCall* method_call) {
556 LOG(INFO) << "ARCVM starting up";
557
558 std::unique_ptr<dbus::Response> dbus_response(
559 dbus::Response::FromMethodCall(method_call));
560
561 dbus::MessageReader reader(method_call);
562 dbus::MessageWriter writer(dbus_response.get());
563
564 patchpanel::ArcVmStartupRequest request;
565 patchpanel::ArcVmStartupResponse response;
566
567 if (!reader.PopArrayOfBytesAsProto(&request)) {
568 LOG(ERROR) << "Unable to parse request";
569 writer.AppendProtoAsArrayOfBytes(response);
570 return dbus_response;
571 }
572
Garrick Evans47c19272019-11-21 10:58:21 +0900573 if (!StartArcVm(request.cid())) {
Garrick Evanse01bf072019-11-15 09:08:19 +0900574 LOG(ERROR) << "Failed to start ARCVM network service";
Garrick Evans47c19272019-11-21 10:58:21 +0900575 writer.AppendProtoAsArrayOfBytes(response);
576 return dbus_response;
Garrick Evanse01bf072019-11-15 09:08:19 +0900577 }
Garrick Evanse94a14e2019-11-11 10:32:13 +0900578
Garrick Evans47c19272019-11-21 10:58:21 +0900579 // Populate the response with the known devices.
Garrick Evans38b25a42020-04-06 15:17:42 +0900580 for (const auto* config : arc_svc_->GetDeviceConfigs()) {
581 if (config->tap_ifname().empty())
582 continue;
Garrick Evans47c19272019-11-21 10:58:21 +0900583
Garrick Evans38b25a42020-04-06 15:17:42 +0900584 auto* dev = response.add_devices();
585 dev->set_ifname(config->tap_ifname());
586 dev->set_ipv4_addr(config->guest_ipv4_addr());
Garrick Evansa0c9c972020-11-30 09:54:59 +0900587 dev->set_guest_type(NetworkDevice::ARCVM);
Garrick Evans38b25a42020-04-06 15:17:42 +0900588 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900589
Garrick Evans08843932019-09-17 14:41:08 +0900590 writer.AppendProtoAsArrayOfBytes(response);
591 return dbus_response;
592}
593
594std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
595 dbus::MethodCall* method_call) {
596 LOG(INFO) << "ARCVM shutting down";
597
598 std::unique_ptr<dbus::Response> dbus_response(
599 dbus::Response::FromMethodCall(method_call));
600
601 dbus::MessageReader reader(method_call);
602 dbus::MessageWriter writer(dbus_response.get());
603
604 patchpanel::ArcVmShutdownRequest request;
605 patchpanel::ArcVmShutdownResponse response;
606
607 if (!reader.PopArrayOfBytesAsProto(&request)) {
608 LOG(ERROR) << "Unable to parse request";
609 writer.AppendProtoAsArrayOfBytes(response);
610 return dbus_response;
611 }
612
Garrick Evans21173b12019-11-20 15:23:16 +0900613 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900614
Garrick Evans08843932019-09-17 14:41:08 +0900615 writer.AppendProtoAsArrayOfBytes(response);
616 return dbus_response;
617}
618
Garrick Evans47c19272019-11-21 10:58:21 +0900619std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
620 dbus::MethodCall* method_call) {
621 LOG(INFO) << "Termina VM starting up";
622
623 std::unique_ptr<dbus::Response> dbus_response(
624 dbus::Response::FromMethodCall(method_call));
625
626 dbus::MessageReader reader(method_call);
627 dbus::MessageWriter writer(dbus_response.get());
628
629 patchpanel::TerminaVmStartupRequest request;
630 patchpanel::TerminaVmStartupResponse response;
631
632 if (!reader.PopArrayOfBytesAsProto(&request)) {
633 LOG(ERROR) << "Unable to parse request";
634 writer.AppendProtoAsArrayOfBytes(response);
635 return dbus_response;
636 }
637
638 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900639 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900640 LOG(ERROR) << "Failed to start Termina VM network service";
641 writer.AppendProtoAsArrayOfBytes(response);
642 return dbus_response;
643 }
644
Garrick Evans51d5b552020-01-30 10:42:06 +0900645 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900646 if (!tap) {
647 LOG(DFATAL) << "TAP device missing";
648 writer.AppendProtoAsArrayOfBytes(response);
649 return dbus_response;
650 }
Garrick Evans47c19272019-11-21 10:58:21 +0900651
Garrick Evansb1c93712020-01-22 09:28:25 +0900652 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900653 dev->set_ifname(tap->host_ifname());
Garrick Evansa0c9c972020-11-30 09:54:59 +0900654 dev->set_guest_type(NetworkDevice::TERMINA_VM);
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900655 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900656 if (!subnet) {
657 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
658 writer.AppendProtoAsArrayOfBytes(response);
659 return dbus_response;
660 }
661 auto* resp_subnet = dev->mutable_ipv4_subnet();
662 resp_subnet->set_base_addr(subnet->BaseAddress());
663 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900664 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900665 if (!subnet) {
666 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
667 writer.AppendProtoAsArrayOfBytes(response);
668 return dbus_response;
669 }
670 resp_subnet = response.mutable_container_subnet();
671 resp_subnet->set_base_addr(subnet->BaseAddress());
672 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900673
674 writer.AppendProtoAsArrayOfBytes(response);
675 return dbus_response;
676}
677
678std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
679 dbus::MethodCall* method_call) {
680 LOG(INFO) << "Termina VM shutting down";
681
682 std::unique_ptr<dbus::Response> dbus_response(
683 dbus::Response::FromMethodCall(method_call));
684
685 dbus::MessageReader reader(method_call);
686 dbus::MessageWriter writer(dbus_response.get());
687
688 patchpanel::TerminaVmShutdownRequest request;
689 patchpanel::TerminaVmShutdownResponse response;
690
691 if (!reader.PopArrayOfBytesAsProto(&request)) {
692 LOG(ERROR) << "Unable to parse request";
693 writer.AppendProtoAsArrayOfBytes(response);
694 return dbus_response;
695 }
696
Garrick Evans51d5b552020-01-30 10:42:06 +0900697 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
698
699 writer.AppendProtoAsArrayOfBytes(response);
700 return dbus_response;
701}
702
703std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
704 dbus::MethodCall* method_call) {
705 LOG(INFO) << "Plugin VM starting up";
706
707 std::unique_ptr<dbus::Response> dbus_response(
708 dbus::Response::FromMethodCall(method_call));
709
710 dbus::MessageReader reader(method_call);
711 dbus::MessageWriter writer(dbus_response.get());
712
713 patchpanel::PluginVmStartupRequest request;
714 patchpanel::PluginVmStartupResponse response;
715
716 if (!reader.PopArrayOfBytesAsProto(&request)) {
717 LOG(ERROR) << "Unable to parse request";
718 writer.AppendProtoAsArrayOfBytes(response);
719 return dbus_response;
720 }
721
Garrick Evans08fb34b2020-02-20 10:50:17 +0900722 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900723 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900724 LOG(ERROR) << "Failed to start Plugin VM network service";
725 writer.AppendProtoAsArrayOfBytes(response);
726 return dbus_response;
727 }
728
729 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
730 if (!tap) {
731 LOG(DFATAL) << "TAP device missing";
732 writer.AppendProtoAsArrayOfBytes(response);
733 return dbus_response;
734 }
735
Garrick Evans51d5b552020-01-30 10:42:06 +0900736 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900737 dev->set_ifname(tap->host_ifname());
Garrick Evansa0c9c972020-11-30 09:54:59 +0900738 dev->set_guest_type(NetworkDevice::PLUGIN_VM);
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900739 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900740 if (!subnet) {
741 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
742 writer.AppendProtoAsArrayOfBytes(response);
743 return dbus_response;
744 }
745 auto* resp_subnet = dev->mutable_ipv4_subnet();
746 resp_subnet->set_base_addr(subnet->BaseAddress());
747 resp_subnet->set_prefix_len(subnet->PrefixLength());
748
749 writer.AppendProtoAsArrayOfBytes(response);
750 return dbus_response;
751}
752
753std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
754 dbus::MethodCall* method_call) {
755 LOG(INFO) << "Plugin VM shutting down";
756
757 std::unique_ptr<dbus::Response> dbus_response(
758 dbus::Response::FromMethodCall(method_call));
759
760 dbus::MessageReader reader(method_call);
761 dbus::MessageWriter writer(dbus_response.get());
762
763 patchpanel::PluginVmShutdownRequest request;
764 patchpanel::PluginVmShutdownResponse response;
765
766 if (!reader.PopArrayOfBytesAsProto(&request)) {
767 LOG(ERROR) << "Unable to parse request";
768 writer.AppendProtoAsArrayOfBytes(response);
769 return dbus_response;
770 }
771
772 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900773
774 writer.AppendProtoAsArrayOfBytes(response);
775 return dbus_response;
776}
777
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900778std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
779 dbus::MethodCall* method_call) {
780 std::unique_ptr<dbus::Response> dbus_response(
781 dbus::Response::FromMethodCall(method_call));
782
783 dbus::MessageReader reader(method_call);
784 dbus::MessageWriter writer(dbus_response.get());
785
786 patchpanel::SetVpnIntentRequest request;
787 patchpanel::SetVpnIntentResponse response;
788
789 bool success = reader.PopArrayOfBytesAsProto(&request);
790 if (!success) {
791 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
792 // Do not return yet to make sure we close the received fd.
793 }
794
795 base::ScopedFD client_socket;
796 reader.PopFileDescriptor(&client_socket);
797
798 if (success)
799 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
800
801 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900802
803 writer.AppendProtoAsArrayOfBytes(response);
804 return dbus_response;
805}
806
807std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
808 dbus::MethodCall* method_call) {
809 std::unique_ptr<dbus::Response> dbus_response(
810 dbus::Response::FromMethodCall(method_call));
811
812 dbus::MessageReader reader(method_call);
813 dbus::MessageWriter writer(dbus_response.get());
814
815 patchpanel::ConnectNamespaceRequest request;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900816
817 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900818 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
819 // Do not return yet to make sure we close the received fd and
820 // validate other arguments.
Hugo Benichi7c342672020-09-08 09:18:14 +0900821 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
822 return dbus_response;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900823 }
824
Hugo Benichicc6850f2020-01-17 13:26:06 +0900825 base::ScopedFD client_fd;
826 reader.PopFileDescriptor(&client_fd);
827 if (!client_fd.is_valid()) {
828 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
Hugo Benichi7c342672020-09-08 09:18:14 +0900829 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
830 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900831 }
832
833 pid_t pid = request.pid();
Garrick Evans263bd952020-12-03 20:27:43 +0900834 if (pid == 1 || pid == getpid()) {
835 LOG(ERROR) << "ConnectNamespaceRequest: privileged namespace pid " << pid;
836 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
837 return dbus_response;
838 }
Hugo Benichicc6850f2020-01-17 13:26:06 +0900839 {
840 ScopedNS ns(pid);
841 if (!ns.IsValid()) {
842 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900843 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
844 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900845 }
846 }
847
848 const std::string& outbound_ifname = request.outbound_physical_device();
849 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
850 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
851 << outbound_ifname;
Hugo Benichi7c342672020-09-08 09:18:14 +0900852 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
853 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900854 }
855
Hugo Benichi7c342672020-09-08 09:18:14 +0900856 auto response = ConnectNamespace(std::move(client_fd), request);
857 writer.AppendProtoAsArrayOfBytes(*response);
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900858 return dbus_response;
859}
860
Jie Jiang493cde42020-07-17 21:43:39 +0900861std::unique_ptr<dbus::Response> Manager::OnGetTrafficCounters(
862 dbus::MethodCall* method_call) {
863 std::unique_ptr<dbus::Response> dbus_response(
864 dbus::Response::FromMethodCall(method_call));
865
866 dbus::MessageReader reader(method_call);
867 dbus::MessageWriter writer(dbus_response.get());
868
869 patchpanel::TrafficCountersRequest request;
870 patchpanel::TrafficCountersResponse response;
871
872 if (!reader.PopArrayOfBytesAsProto(&request)) {
873 LOG(ERROR) << "Unable to parse TrafficCountersRequest";
874 writer.AppendProtoAsArrayOfBytes(response);
875 return dbus_response;
876 }
877
878 const std::set<std::string> devices{request.devices().begin(),
879 request.devices().end()};
Hugo Benichi1df64172020-12-13 22:59:01 +0900880 // TODO(b/175364240) Find why iptables -L -x -v -w can freeze on
881 // writing to stdout and in turn block patchpanel.
882 /*
Jie Jiang493cde42020-07-17 21:43:39 +0900883 const auto counters = counters_svc_->GetCounters(devices);
884 for (const auto& kv : counters) {
885 auto* traffic_counter = response.add_counters();
886 const auto& source_and_device = kv.first;
887 const auto& counter = kv.second;
888 traffic_counter->set_source(source_and_device.first);
889 traffic_counter->set_device(source_and_device.second);
890 traffic_counter->set_rx_bytes(counter.rx_bytes);
891 traffic_counter->set_rx_packets(counter.rx_packets);
892 traffic_counter->set_tx_bytes(counter.tx_bytes);
893 traffic_counter->set_tx_packets(counter.tx_packets);
894 }
Hugo Benichi1df64172020-12-13 22:59:01 +0900895 */
Jie Jiang493cde42020-07-17 21:43:39 +0900896
897 writer.AppendProtoAsArrayOfBytes(response);
898 return dbus_response;
899}
900
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900901std::unique_ptr<dbus::Response> Manager::OnModifyPortRule(
902 dbus::MethodCall* method_call) {
903 std::unique_ptr<dbus::Response> dbus_response(
904 dbus::Response::FromMethodCall(method_call));
905
906 dbus::MessageReader reader(method_call);
907 dbus::MessageWriter writer(dbus_response.get());
908
909 patchpanel::ModifyPortRuleRequest request;
910 patchpanel::ModifyPortRuleResponse response;
911
912 if (!reader.PopArrayOfBytesAsProto(&request)) {
913 LOG(ERROR) << "Unable to parse ModifyPortRequest";
914 writer.AppendProtoAsArrayOfBytes(response);
915 return dbus_response;
916 }
917
Jason Jeremy Imanc28df852020-07-11 17:38:26 +0900918 response.set_success(ModifyPortRule(request));
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900919 writer.AppendProtoAsArrayOfBytes(response);
920 return dbus_response;
921}
922
Jie Jiang25c1b972020-11-12 15:42:53 +0900923void Manager::OnNeighborReachabilityEvent(
Jie Jiang84966852020-09-18 18:49:05 +0900924 int ifindex,
925 const shill::IPAddress& ip_addr,
926 NeighborLinkMonitor::NeighborRole role,
Jie Jiang25c1b972020-11-12 15:42:53 +0900927 NeighborReachabilityEventSignal::EventType event_type) {
Jie Jiang84966852020-09-18 18:49:05 +0900928 if (!ip_addr.IsValid()) {
929 LOG(DFATAL) << "ip_addr is not valid";
930 return;
931 }
932
Jie Jiang25c1b972020-11-12 15:42:53 +0900933 using SignalProto = NeighborReachabilityEventSignal;
Jie Jiang84966852020-09-18 18:49:05 +0900934 SignalProto proto;
935 proto.set_ifindex(ifindex);
936 proto.set_ip_addr(ip_addr.ToString());
Jie Jiang25c1b972020-11-12 15:42:53 +0900937 proto.set_type(event_type);
Jie Jiang84966852020-09-18 18:49:05 +0900938 switch (role) {
939 case NeighborLinkMonitor::NeighborRole::kGateway:
940 proto.set_role(SignalProto::GATEWAY);
941 break;
942 case NeighborLinkMonitor::NeighborRole::kDNSServer:
943 proto.set_role(SignalProto::DNS_SERVER);
944 break;
945 case NeighborLinkMonitor::NeighborRole::kGatewayAndDNSServer:
946 proto.set_role(SignalProto::GATEWAY_AND_DNS_SERVER);
947 break;
948 default:
949 NOTREACHED();
950 }
951
Jie Jiang25c1b972020-11-12 15:42:53 +0900952 dbus::Signal signal(kPatchPanelInterface, kNeighborReachabilityEventSignal);
Jie Jiang84966852020-09-18 18:49:05 +0900953 dbus::MessageWriter writer(&signal);
954 if (!writer.AppendProtoAsArrayOfBytes(proto)) {
Jie Jiang25c1b972020-11-12 15:42:53 +0900955 LOG(ERROR) << "Failed to encode proto NeighborReachabilityEventSignal";
Jie Jiang84966852020-09-18 18:49:05 +0900956 return;
957 }
958
959 dbus_svc_path_->SendSignal(&signal);
960}
961
Hugo Benichi7c342672020-09-08 09:18:14 +0900962std::unique_ptr<patchpanel::ConnectNamespaceResponse> Manager::ConnectNamespace(
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900963 base::ScopedFD client_fd,
Hugo Benichi7c342672020-09-08 09:18:14 +0900964 const patchpanel::ConnectNamespaceRequest& request) {
965 auto response = std::make_unique<patchpanel::ConnectNamespaceResponse>();
966
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900967 std::unique_ptr<Subnet> subnet =
968 addr_mgr_.AllocateIPv4Subnet(AddressManager::Guest::MINIJAIL_NETNS);
969 if (!subnet) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900970 LOG(ERROR) << "ConnectNamespace: exhausted IPv4 subnet space";
971 return response;
Hugo Benichie8758b52020-04-03 14:49:01 +0900972 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900973
Hugo Benichi7352ad92020-04-07 16:11:59 +0900974 // Dup the client fd into our own: this guarantees that the fd number will
975 // be stable and tied to the actual kernel resources used by the client.
976 base::ScopedFD local_client_fd(dup(client_fd.get()));
977 if (!local_client_fd.is_valid()) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900978 PLOG(ERROR) << "ConnectNamespace: failed to dup() client fd";
979 return response;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900980 }
981
Hugo Benichi7c342672020-09-08 09:18:14 +0900982 // Add the duped fd to the epoll watcher.
Hugo Benichi7352ad92020-04-07 16:11:59 +0900983 // TODO(hugobenichi) Find a way to reuse base::FileDescriptorWatcher for
984 // listening to EPOLLHUP.
985 struct epoll_event epevent;
986 epevent.events = EPOLLIN; // EPOLLERR | EPOLLHUP are always waited for.
987 epevent.data.fd = local_client_fd.get();
988 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_ADD,
989 local_client_fd.get(), &epevent) != 0) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900990 PLOG(ERROR) << "ConnectNamespace: epoll_ctl(EPOLL_CTL_ADD) failed";
991 return response;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900992 }
993
Hugo Benichi7c342672020-09-08 09:18:14 +0900994 const std::string ifname_id = std::to_string(connected_namespaces_next_id_);
Hugo Benichifcf81022020-12-04 11:01:37 +0900995 ConnectedNamespace nsinfo = {};
996 nsinfo.pid = request.pid();
997 nsinfo.netns_name = "connected_netns_" + ifname_id;
Hugo Benichi93306e52020-12-04 16:08:00 +0900998 nsinfo.source = ProtoToTrafficSource(request.traffic_source());
999 if (nsinfo.source == TrafficSource::UNKNOWN)
1000 nsinfo.source = TrafficSource::SYSTEM;
Hugo Benichifcf81022020-12-04 11:01:37 +09001001 nsinfo.outbound_ifname = request.outbound_physical_device();
Hugo Benichi93306e52020-12-04 16:08:00 +09001002 nsinfo.route_on_vpn = request.route_on_vpn();
Hugo Benichifcf81022020-12-04 11:01:37 +09001003 nsinfo.host_ifname = "arc_ns" + ifname_id;
1004 nsinfo.peer_ifname = "veth" + ifname_id;
1005 nsinfo.peer_subnet = std::move(subnet);
1006 nsinfo.peer_mac_addr = addr_mgr_.GenerateMacAddress();
1007
1008 if (!datapath_->StartRoutingNamespace(nsinfo)) {
Hugo Benichi7c342672020-09-08 09:18:14 +09001009 LOG(ERROR) << "ConnectNamespace: failed to setup datapath";
1010 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL,
1011 local_client_fd.get(), nullptr) != 0)
1012 PLOG(ERROR) << "ConnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
1013 return response;
1014 }
1015
Hugo Benichifcf81022020-12-04 11:01:37 +09001016 // Prepare the response before storing ConnectedNamespace.
1017 response->set_peer_ifname(nsinfo.peer_ifname);
1018 response->set_peer_ipv4_address(nsinfo.peer_subnet->AddressAtOffset(1));
1019 response->set_host_ifname(nsinfo.host_ifname);
1020 response->set_host_ipv4_address(nsinfo.peer_subnet->AddressAtOffset(0));
Hugo Benichi7c342672020-09-08 09:18:14 +09001021 auto* response_subnet = response->mutable_ipv4_subnet();
Hugo Benichifcf81022020-12-04 11:01:37 +09001022 response_subnet->set_base_addr(nsinfo.peer_subnet->BaseAddress());
1023 response_subnet->set_prefix_len(nsinfo.peer_subnet->PrefixLength());
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001024
Hugo Benichifcf81022020-12-04 11:01:37 +09001025 LOG(INFO) << "Connected network namespace " << nsinfo;
1026
1027 // Store ConnectedNamespace
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001028 connected_namespaces_next_id_++;
Hugo Benichi7352ad92020-04-07 16:11:59 +09001029 int fdkey = local_client_fd.release();
Hugo Benichifcf81022020-12-04 11:01:37 +09001030 connected_namespaces_.insert(std::make_pair(fdkey, std::move(nsinfo)));
Hugo Benichi7352ad92020-04-07 16:11:59 +09001031
1032 if (connected_namespaces_.size() == 1) {
1033 LOG(INFO) << "Starting ConnectNamespace client fds monitoring";
1034 CheckConnectedNamespaces();
1035 }
Hugo Benichi7c342672020-09-08 09:18:14 +09001036
1037 return response;
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001038}
1039
1040void Manager::DisconnectNamespace(int client_fd) {
1041 auto it = connected_namespaces_.find(client_fd);
1042 if (it == connected_namespaces_.end()) {
Hugo Benichifcf81022020-12-04 11:01:37 +09001043 LOG(ERROR) << "No ConnectedNamespace found for client_fd " << client_fd;
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001044 return;
1045 }
1046
Hugo Benichi7352ad92020-04-07 16:11:59 +09001047 // Remove the client fd dupe from the epoll watcher and close it.
1048 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL, client_fd,
Hugo Benichie8758b52020-04-03 14:49:01 +09001049 nullptr) != 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +09001050 PLOG(ERROR) << "DisconnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +09001051 if (close(client_fd) < 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +09001052 PLOG(ERROR) << "DisconnectNamespace: close(client_fd) failed";
Hugo Benichi7352ad92020-04-07 16:11:59 +09001053
Hugo Benichifcf81022020-12-04 11:01:37 +09001054 datapath_->StopRoutingNamespace(it->second);
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001055 LOG(INFO) << "Disconnected network namespace " << it->second;
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001056 // This release the allocated IPv4 subnet.
1057 connected_namespaces_.erase(it);
1058}
1059
Hugo Benichi7352ad92020-04-07 16:11:59 +09001060// TODO(hugobenichi) Generalize this check to all resources created by
1061// patchpanel on behalf of a remote client.
1062void Manager::CheckConnectedNamespaces() {
1063 int max_event = 10;
1064 struct epoll_event epevents[max_event];
1065 int nready = epoll_wait(connected_namespaces_epollfd_, epevents, max_event,
1066 0 /* do not block */);
1067 if (nready < 0)
1068 PLOG(ERROR) << "CheckConnectedNamespaces: epoll_wait(0) failed";
1069
1070 for (int i = 0; i < nready; i++)
1071 if (epevents[i].events & (EPOLLHUP | EPOLLERR))
1072 DisconnectNamespace(epevents[i].data.fd);
1073
1074 if (connected_namespaces_.empty()) {
1075 LOG(INFO) << "Stopping ConnectNamespace client fds monitoring";
1076 return;
1077 }
1078
Qijiang Fan2d7aeb42020-05-19 02:06:39 +09001079 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Hugo Benichi7352ad92020-04-07 16:11:59 +09001080 FROM_HERE,
1081 base::Bind(&Manager::CheckConnectedNamespaces,
Hugo Benichie8758b52020-04-03 14:49:01 +09001082 weak_factory_.GetWeakPtr()),
Hugo Benichi7352ad92020-04-07 16:11:59 +09001083 kConnectNamespaceCheckInterval);
1084}
1085
Jason Jeremy Imanc28df852020-07-11 17:38:26 +09001086bool Manager::ModifyPortRule(const patchpanel::ModifyPortRuleRequest& request) {
1087 switch (request.proto()) {
1088 case patchpanel::ModifyPortRuleRequest::TCP:
1089 case patchpanel::ModifyPortRuleRequest::UDP:
1090 break;
1091 default:
1092 LOG(ERROR) << "Unknown protocol " << request.proto();
1093 return false;
1094 }
1095
1096 switch (request.op()) {
1097 case patchpanel::ModifyPortRuleRequest::CREATE:
1098 switch (request.type()) {
1099 case patchpanel::ModifyPortRuleRequest::ACCESS:
1100 return firewall_.AddAcceptRules(request.proto(),
1101 request.input_dst_port(),
1102 request.input_ifname());
1103 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
1104 return firewall_.AddLoopbackLockdownRules(request.proto(),
1105 request.input_dst_port());
1106 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1107 return firewall_.AddIpv4ForwardRule(
1108 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1109 request.input_ifname(), request.dst_ip(), request.dst_port());
1110 default:
1111 LOG(ERROR) << "Unknown port rule type " << request.type();
1112 return false;
1113 }
1114 case patchpanel::ModifyPortRuleRequest::DELETE:
1115 switch (request.type()) {
1116 case patchpanel::ModifyPortRuleRequest::ACCESS:
1117 return firewall_.DeleteAcceptRules(request.proto(),
1118 request.input_dst_port(),
1119 request.input_ifname());
1120 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
1121 return firewall_.DeleteLoopbackLockdownRules(
1122 request.proto(), request.input_dst_port());
1123 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1124 return firewall_.DeleteIpv4ForwardRule(
1125 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1126 request.input_ifname(), request.dst_ip(), request.dst_port());
1127 default:
1128 LOG(ERROR) << "Unknown port rule type " << request.type();
1129 return false;
1130 }
1131 default:
1132 LOG(ERROR) << "Unknown operation " << request.op();
1133 return false;
1134 }
1135}
1136
Garrick Evanse94a14e2019-11-11 10:32:13 +09001137void Manager::SendGuestMessage(const GuestMessage& msg) {
Garrick Evans96e03042019-05-28 14:30:52 +09001138 IpHelperMessage ipm;
1139 *ipm.mutable_guest_message() = msg;
Garrick Evans96e03042019-05-28 14:30:52 +09001140 adb_proxy_->SendMessage(ipm);
Garrick Evanse94a14e2019-11-11 10:32:13 +09001141 mcast_proxy_->SendMessage(ipm);
1142 nd_proxy_->SendMessage(ipm);
Garrick Evans96e03042019-05-28 14:30:52 +09001143}
1144
Garrick Evans4ac09852020-01-16 14:09:22 +09001145void Manager::StartForwarding(const std::string& ifname_physical,
1146 const std::string& ifname_virtual,
Garrick Evans4ac09852020-01-16 14:09:22 +09001147 bool ipv6,
1148 bool multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001149 if (ifname_physical.empty() || ifname_virtual.empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001150 return;
1151
1152 IpHelperMessage ipm;
1153 DeviceMessage* msg = ipm.mutable_device_message();
1154 msg->set_dev_ifname(ifname_physical);
Garrick Evans4ac09852020-01-16 14:09:22 +09001155 msg->set_br_ifname(ifname_virtual);
1156
1157 if (ipv6) {
1158 LOG(INFO) << "Starting IPv6 forwarding from " << ifname_physical << " to "
1159 << ifname_virtual;
1160
1161 if (!datapath_->AddIPv6Forwarding(ifname_physical, ifname_virtual)) {
1162 LOG(ERROR) << "Failed to setup iptables forwarding rule for IPv6 from "
1163 << ifname_physical << " to " << ifname_virtual;
1164 }
1165 if (!datapath_->MaskInterfaceFlags(ifname_physical, IFF_ALLMULTI)) {
1166 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1167 << ifname_physical;
1168 }
1169 if (!datapath_->MaskInterfaceFlags(ifname_virtual, IFF_ALLMULTI)) {
1170 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1171 << ifname_virtual;
1172 }
1173 nd_proxy_->SendMessage(ipm);
1174 }
1175
1176 if (multicast) {
1177 LOG(INFO) << "Starting multicast forwarding from " << ifname_physical
1178 << " to " << ifname_virtual;
1179 mcast_proxy_->SendMessage(ipm);
1180 }
1181}
1182
1183void Manager::StopForwarding(const std::string& ifname_physical,
1184 const std::string& ifname_virtual,
1185 bool ipv6,
1186 bool multicast) {
1187 if (ifname_physical.empty())
1188 return;
1189
1190 IpHelperMessage ipm;
1191 DeviceMessage* msg = ipm.mutable_device_message();
1192 msg->set_dev_ifname(ifname_physical);
1193 msg->set_teardown(true);
Taoyu Li7dca19a2020-03-16 16:27:07 +09001194 if (!ifname_virtual.empty()) {
1195 msg->set_br_ifname(ifname_virtual);
1196 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001197
1198 if (ipv6) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001199 if (ifname_virtual.empty()) {
1200 LOG(INFO) << "Stopping IPv6 forwarding on " << ifname_physical;
1201 } else {
1202 LOG(INFO) << "Stopping IPv6 forwarding from " << ifname_physical << " to "
1203 << ifname_virtual;
1204 datapath_->RemoveIPv6Forwarding(ifname_physical, ifname_virtual);
1205 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001206 nd_proxy_->SendMessage(ipm);
1207 }
1208
1209 if (multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001210 if (ifname_virtual.empty()) {
1211 LOG(INFO) << "Stopping multicast forwarding on " << ifname_physical;
1212 } else {
1213 LOG(INFO) << "Stopping multicast forwarding from " << ifname_physical
1214 << " to " << ifname_virtual;
1215 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001216 mcast_proxy_->SendMessage(ipm);
1217 }
1218}
1219
Taoyu Lia0727dc2020-09-24 19:54:59 +09001220void Manager::OnNDProxyMessage(const NDProxyMessage& msg) {
1221 LOG_IF(DFATAL, msg.ifname().empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001222 << "Received DeviceMessage w/ empty dev_ifname";
Taoyu Lia0727dc2020-09-24 19:54:59 +09001223 switch (msg.type()) {
1224 case NDProxyMessage::ADD_ROUTE:
1225 if (!datapath_->AddIPv6HostRoute(msg.ifname(), msg.ip6addr(), 128)) {
1226 LOG(WARNING) << "Failed to setup the IPv6 route for interface "
1227 << msg.ifname() << ", addr " << msg.ip6addr();
1228 }
1229 break;
1230 case NDProxyMessage::ADD_ADDR:
1231 if (!datapath_->AddIPv6Address(msg.ifname(), msg.ip6addr())) {
1232 LOG(WARNING) << "Failed to setup the IPv6 address for interface "
1233 << msg.ifname() << ", addr " << msg.ip6addr();
1234 }
1235 break;
1236 case NDProxyMessage::DEL_ADDR:
1237 datapath_->RemoveIPv6Address(msg.ifname(), msg.ip6addr());
1238 break;
1239 default:
1240 LOG(ERROR) << "Unknown NDProxy event " << msg.type();
1241 NOTREACHED();
Garrick Evans4ac09852020-01-16 14:09:22 +09001242 }
1243}
1244
Garrick Evans3388a032020-03-24 11:25:55 +09001245} // namespace patchpanel