blob: 71b0f87c2643709a1a6a0400904f61298854b465 [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()));
227 }
Hugo Benichifda77232020-08-21 18:28:15 +0900228
Taoyu Lia0727dc2020-09-24 19:54:59 +0900229 nd_proxy_->RegisterNDProxyMessageHandler(
230 base::Bind(&Manager::OnNDProxyMessage, weak_factory_.GetWeakPtr()));
Hugo Benichifda77232020-08-21 18:28:15 +0900231
Hugo Benichifda77232020-08-21 18:28:15 +0900232 auto* const forwarder = static_cast<TrafficForwarder*>(this);
233
234 GuestMessage::GuestType arc_guest =
235 USE_ARCVM ? GuestMessage::ARC_VM : GuestMessage::ARC;
Garrick Evans209a80a2020-11-30 14:42:40 +0900236 arc_svc_ = std::make_unique<ArcService>(
237 shill_client_.get(), datapath_.get(), &addr_mgr_, forwarder, arc_guest,
238 base::BindRepeating(&Manager::OnDeviceChanged,
239 weak_factory_.GetWeakPtr()));
240 cros_svc_ = std::make_unique<CrostiniService>(
241 shill_client_.get(), &addr_mgr_, datapath_.get(), forwarder,
242 base::BindRepeating(&Manager::OnDeviceChanged,
243 weak_factory_.GetWeakPtr()));
Jie Jiang84966852020-09-18 18:49:05 +0900244 network_monitor_svc_ = std::make_unique<NetworkMonitorService>(
245 shill_client_.get(),
Jie Jiang25c1b972020-11-12 15:42:53 +0900246 base::BindRepeating(&Manager::OnNeighborReachabilityEvent,
Jie Jiang84966852020-09-18 18:49:05 +0900247 weak_factory_.GetWeakPtr()));
Hugo Benichifda77232020-08-21 18:28:15 +0900248 network_monitor_svc_->Start();
Hugo Benichi058a26a2020-11-26 10:10:39 +0900249 counters_svc_->Init(shill_client_->get_devices());
Hugo Benichifda77232020-08-21 18:28:15 +0900250 nd_proxy_->Listen();
251}
252
253void Manager::OnShutdown(int* exit_code) {
254 LOG(INFO) << "Shutting down and cleaning up";
Jie Jiang84966852020-09-18 18:49:05 +0900255 network_monitor_svc_.reset();
Hugo Benichifda77232020-08-21 18:28:15 +0900256 cros_svc_.reset();
257 arc_svc_.reset();
258 close(connected_namespaces_epollfd_);
259 // Tear down any remaining connected namespace.
260 std::vector<int> connected_namespaces_fdkeys;
261 for (const auto& kv : connected_namespaces_)
262 connected_namespaces_fdkeys.push_back(kv.first);
263 for (const int fdkey : connected_namespaces_fdkeys)
264 DisconnectNamespace(fdkey);
Hugo Benichibf811c62020-09-07 17:30:45 +0900265 if (!USE_JETSTREAM_ROUTING)
266 datapath_->Stop();
Jie Jiang00592cf2020-12-17 11:23:49 +0900267
268 brillo::DBusDaemon::OnShutdown(exit_code);
Hugo Benichifda77232020-08-21 18:28:15 +0900269}
270
271void Manager::OnSubprocessExited(pid_t pid, const siginfo_t&) {
272 LOG(ERROR) << "Subprocess " << pid << " exited unexpectedly -"
273 << " attempting to restart";
274
275 HelperProcess* proc;
276 if (pid == adb_proxy_->pid()) {
277 proc = adb_proxy_.get();
278 } else if (pid == mcast_proxy_->pid()) {
279 proc = mcast_proxy_.get();
280 } else if (pid == nd_proxy_->pid()) {
281 proc = nd_proxy_.get();
282 } else {
283 LOG(DFATAL) << "Unknown child process";
284 return;
285 }
286
287 process_reaper_.ForgetChild(pid);
288
289 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
290 FROM_HERE,
291 base::Bind(&Manager::RestartSubprocess, weak_factory_.GetWeakPtr(), proc),
292 base::TimeDelta::FromMilliseconds((2 << proc->restarts()) *
293 kSubprocessRestartDelayMs));
294}
295
296void Manager::RestartSubprocess(HelperProcess* subproc) {
297 if (subproc->Restart()) {
298 DCHECK(process_reaper_.WatchForChild(
299 FROM_HERE, subproc->pid(),
300 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
301 subproc->pid())))
302 << "Failed to watch child process " << subproc->pid();
303 }
304}
305
Hugo Benichi2a940542020-10-26 18:50:49 +0900306void Manager::OnDefaultDeviceChanged(const ShillClient::Device& new_device,
307 const ShillClient::Device& prev_device) {
308 // Only take into account interface switches and ignore layer 3 property
309 // changes.
310 if (prev_device.ifname == new_device.ifname)
311 return;
312
Hugo Benichi058a26a2020-11-26 10:10:39 +0900313 if (prev_device.type == ShillClient::Device::Type::kVPN) {
Hugo Benichi2a940542020-10-26 18:50:49 +0900314 datapath_->StopVpnRouting(prev_device.ifname);
Hugo Benichi058a26a2020-11-26 10:10:39 +0900315 counters_svc_->OnVpnDeviceRemoved(prev_device.ifname);
316 }
Hugo Benichi2a940542020-10-26 18:50:49 +0900317
Hugo Benichi058a26a2020-11-26 10:10:39 +0900318 if (new_device.type == ShillClient::Device::Type::kVPN) {
Hugo Benichi2a940542020-10-26 18:50:49 +0900319 datapath_->StartVpnRouting(new_device.ifname);
Hugo Benichi058a26a2020-11-26 10:10:39 +0900320 counters_svc_->OnVpnDeviceAdded(new_device.ifname);
321 }
Hugo Benichi2a940542020-10-26 18:50:49 +0900322}
323
Hugo Benichi76be34a2020-08-26 22:35:54 +0900324void Manager::OnDevicesChanged(const std::set<std::string>& added,
325 const std::set<std::string>& removed) {
Hugo Benichi058a26a2020-11-26 10:10:39 +0900326 for (const std::string& ifname : removed) {
Hugo Benichi76be34a2020-08-26 22:35:54 +0900327 datapath_->StopConnectionPinning(ifname);
Hugo Benichi058a26a2020-11-26 10:10:39 +0900328 counters_svc_->OnPhysicalDeviceRemoved(ifname);
329 }
Hugo Benichi76be34a2020-08-26 22:35:54 +0900330
Hugo Benichi058a26a2020-11-26 10:10:39 +0900331 for (const std::string& ifname : added) {
Hugo Benichi76be34a2020-08-26 22:35:54 +0900332 datapath_->StartConnectionPinning(ifname);
Hugo Benichi058a26a2020-11-26 10:10:39 +0900333 counters_svc_->OnPhysicalDeviceAdded(ifname);
334 }
Hugo Benichi76be34a2020-08-26 22:35:54 +0900335}
336
Garrick Evans209a80a2020-11-30 14:42:40 +0900337void Manager::OnDeviceChanged(const Device& device,
338 Device::ChangeEvent event,
339 GuestMessage::GuestType guest_type) {
340 dbus::Signal signal(kPatchPanelInterface, kNetworkDeviceChangedSignal);
341 NetworkDeviceChangedSignal proto;
342 proto.set_event(event == Device::ChangeEvent::ADDED
343 ? NetworkDeviceChangedSignal::DEVICE_ADDED
344 : NetworkDeviceChangedSignal::DEVICE_REMOVED);
345 auto* dev = proto.mutable_device();
346 dev->set_ifname(device.host_ifname());
347 dev->set_ipv4_addr(device.config().guest_ipv4_addr());
348 if (const auto* subnet = device.config().ipv4_subnet()) {
349 auto* sub = dev->mutable_ipv4_subnet();
350 sub->set_base_addr(subnet->BaseAddress());
351 sub->set_prefix_len(subnet->PrefixLength());
352 }
353 switch (guest_type) {
354 case GuestMessage::ARC:
355 dev->set_guest_type(NetworkDevice::ARC);
356 break;
357 case GuestMessage::ARC_VM:
358 dev->set_guest_type(NetworkDevice::ARCVM);
359 break;
360 case GuestMessage::TERMINA_VM:
361 dev->set_guest_type(NetworkDevice::TERMINA_VM);
362 break;
363 case GuestMessage::PLUGIN_VM:
364 dev->set_guest_type(NetworkDevice::PLUGIN_VM);
365 break;
366 default:
367 LOG(ERROR) << "Unknown device type";
368 }
369
370 dbus::MessageWriter(&signal).AppendProtoAsArrayOfBytes(proto);
371 dbus_svc_path_->SendSignal(&signal);
372}
373
Garrick Evanse94a14e2019-11-11 10:32:13 +0900374bool Manager::StartArc(pid_t pid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900375 if (!arc_svc_->Start(pid))
376 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900377
378 GuestMessage msg;
379 msg.set_event(GuestMessage::START);
380 msg.set_type(GuestMessage::ARC);
381 msg.set_arc_pid(pid);
382 SendGuestMessage(msg);
383
384 return true;
385}
386
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900387void Manager::StopArc() {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900388 GuestMessage msg;
389 msg.set_event(GuestMessage::STOP);
390 msg.set_type(GuestMessage::ARC);
391 SendGuestMessage(msg);
392
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900393 // After the ARC container has stopped, the pid is not known anymore.
394 // The pid argument is ignored by ArcService.
395 arc_svc_->Stop(0);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900396}
397
Garrick Evans015b0d62020-02-07 09:06:38 +0900398bool Manager::StartArcVm(uint32_t cid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900399 if (!arc_svc_->Start(cid))
400 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900401
402 GuestMessage msg;
403 msg.set_event(GuestMessage::START);
404 msg.set_type(GuestMessage::ARC_VM);
405 msg.set_arcvm_vsock_cid(cid);
406 SendGuestMessage(msg);
407
408 return true;
409}
410
Garrick Evans015b0d62020-02-07 09:06:38 +0900411void Manager::StopArcVm(uint32_t cid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900412 GuestMessage msg;
413 msg.set_event(GuestMessage::STOP);
414 msg.set_type(GuestMessage::ARC_VM);
415 SendGuestMessage(msg);
416
Garrick Evans21173b12019-11-20 15:23:16 +0900417 arc_svc_->Stop(cid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900418}
419
Garrick Evans51d5b552020-01-30 10:42:06 +0900420bool Manager::StartCrosVm(uint64_t vm_id,
421 GuestMessage::GuestType vm_type,
Garrick Evans53a2a982020-02-05 10:53:35 +0900422 uint32_t subnet_index) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900423 DCHECK(vm_type == GuestMessage::TERMINA_VM ||
424 vm_type == GuestMessage::PLUGIN_VM);
425
426 if (!cros_svc_->Start(vm_id, vm_type == GuestMessage::TERMINA_VM,
427 subnet_index))
Garrick Evans47c19272019-11-21 10:58:21 +0900428 return false;
429
430 GuestMessage msg;
431 msg.set_event(GuestMessage::START);
Garrick Evans51d5b552020-01-30 10:42:06 +0900432 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900433 SendGuestMessage(msg);
434
435 return true;
436}
437
Garrick Evans51d5b552020-01-30 10:42:06 +0900438void Manager::StopCrosVm(uint64_t vm_id, GuestMessage::GuestType vm_type) {
Garrick Evans47c19272019-11-21 10:58:21 +0900439 GuestMessage msg;
440 msg.set_event(GuestMessage::STOP);
Garrick Evans51d5b552020-01-30 10:42:06 +0900441 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900442 SendGuestMessage(msg);
443
Garrick Evans51d5b552020-01-30 10:42:06 +0900444 cros_svc_->Stop(vm_id, vm_type == GuestMessage::TERMINA_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900445}
446
Garrick Evans02e6e872020-11-30 11:53:13 +0900447std::unique_ptr<dbus::Response> Manager::OnGetDevices(
448 dbus::MethodCall* method_call) {
449 std::unique_ptr<dbus::Response> dbus_response(
450 dbus::Response::FromMethodCall(method_call));
451
452 dbus::MessageReader reader(method_call);
453 dbus::MessageWriter writer(dbus_response.get());
454
455 patchpanel::GetDevicesRequest request;
456 patchpanel::GetDevicesResponse response;
457
458 if (!reader.PopArrayOfBytesAsProto(&request)) {
459 LOG(ERROR) << "Unable to parse request";
460 writer.AppendProtoAsArrayOfBytes(response);
461 return dbus_response;
462 }
463
464 static const auto arc_guest_type =
465 USE_ARCVM ? NetworkDevice::ARCVM : NetworkDevice::ARC;
466
467 arc_svc_->ScanDevices(base::BindRepeating(
468 [](patchpanel::GetDevicesResponse* resp, const Device& device) {
469 auto* dev = resp->add_devices();
470 dev->set_ifname(device.host_ifname());
471 dev->set_ipv4_addr(device.config().guest_ipv4_addr());
472 dev->set_guest_type(arc_guest_type);
473 if (const auto* subnet = device.config().ipv4_subnet()) {
474 auto* sub = dev->mutable_ipv4_subnet();
475 sub->set_base_addr(subnet->BaseAddress());
476 sub->set_prefix_len(subnet->PrefixLength());
477 }
478 },
479 &response));
480
481 cros_svc_->ScanDevices(base::BindRepeating(
482 [](patchpanel::GetDevicesResponse* resp, uint64_t vm_id, bool is_termina,
483 const Device& device) {
484 auto* dev = resp->add_devices();
485 dev->set_ifname(device.host_ifname());
486 dev->set_ipv4_addr(device.config().guest_ipv4_addr());
487 dev->set_guest_type(is_termina ? NetworkDevice::TERMINA_VM
488 : NetworkDevice::PLUGIN_VM);
489 if (const auto* subnet = device.config().ipv4_subnet()) {
490 auto* sub = dev->mutable_ipv4_subnet();
491 sub->set_base_addr(subnet->BaseAddress());
492 sub->set_prefix_len(subnet->PrefixLength());
493 }
494 },
495 &response));
496
497 writer.AppendProtoAsArrayOfBytes(response);
498 return dbus_response;
499}
500
Garrick Evans08843932019-09-17 14:41:08 +0900501std::unique_ptr<dbus::Response> Manager::OnArcStartup(
502 dbus::MethodCall* method_call) {
503 LOG(INFO) << "ARC++ starting up";
504
505 std::unique_ptr<dbus::Response> dbus_response(
506 dbus::Response::FromMethodCall(method_call));
507
508 dbus::MessageReader reader(method_call);
509 dbus::MessageWriter writer(dbus_response.get());
510
511 patchpanel::ArcStartupRequest request;
512 patchpanel::ArcStartupResponse response;
513
514 if (!reader.PopArrayOfBytesAsProto(&request)) {
515 LOG(ERROR) << "Unable to parse request";
516 writer.AppendProtoAsArrayOfBytes(response);
517 return dbus_response;
518 }
519
Garrick Evanse01bf072019-11-15 09:08:19 +0900520 if (!StartArc(request.pid()))
521 LOG(ERROR) << "Failed to start ARC++ network service";
Garrick Evanse94a14e2019-11-11 10:32:13 +0900522
Garrick Evans08843932019-09-17 14:41:08 +0900523 writer.AppendProtoAsArrayOfBytes(response);
524 return dbus_response;
525}
526
527std::unique_ptr<dbus::Response> Manager::OnArcShutdown(
528 dbus::MethodCall* method_call) {
529 LOG(INFO) << "ARC++ shutting down";
530
531 std::unique_ptr<dbus::Response> dbus_response(
532 dbus::Response::FromMethodCall(method_call));
533
534 dbus::MessageReader reader(method_call);
535 dbus::MessageWriter writer(dbus_response.get());
536
537 patchpanel::ArcShutdownRequest request;
538 patchpanel::ArcShutdownResponse response;
539
540 if (!reader.PopArrayOfBytesAsProto(&request)) {
541 LOG(ERROR) << "Unable to parse request";
542 writer.AppendProtoAsArrayOfBytes(response);
543 return dbus_response;
544 }
545
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900546 StopArc();
Garrick Evanse94a14e2019-11-11 10:32:13 +0900547
Garrick Evans08843932019-09-17 14:41:08 +0900548 writer.AppendProtoAsArrayOfBytes(response);
549 return dbus_response;
550}
551
552std::unique_ptr<dbus::Response> Manager::OnArcVmStartup(
553 dbus::MethodCall* method_call) {
554 LOG(INFO) << "ARCVM starting up";
555
556 std::unique_ptr<dbus::Response> dbus_response(
557 dbus::Response::FromMethodCall(method_call));
558
559 dbus::MessageReader reader(method_call);
560 dbus::MessageWriter writer(dbus_response.get());
561
562 patchpanel::ArcVmStartupRequest request;
563 patchpanel::ArcVmStartupResponse response;
564
565 if (!reader.PopArrayOfBytesAsProto(&request)) {
566 LOG(ERROR) << "Unable to parse request";
567 writer.AppendProtoAsArrayOfBytes(response);
568 return dbus_response;
569 }
570
Garrick Evans47c19272019-11-21 10:58:21 +0900571 if (!StartArcVm(request.cid())) {
Garrick Evanse01bf072019-11-15 09:08:19 +0900572 LOG(ERROR) << "Failed to start ARCVM network service";
Garrick Evans47c19272019-11-21 10:58:21 +0900573 writer.AppendProtoAsArrayOfBytes(response);
574 return dbus_response;
Garrick Evanse01bf072019-11-15 09:08:19 +0900575 }
Garrick Evanse94a14e2019-11-11 10:32:13 +0900576
Garrick Evans47c19272019-11-21 10:58:21 +0900577 // Populate the response with the known devices.
Garrick Evans38b25a42020-04-06 15:17:42 +0900578 for (const auto* config : arc_svc_->GetDeviceConfigs()) {
579 if (config->tap_ifname().empty())
580 continue;
Garrick Evans47c19272019-11-21 10:58:21 +0900581
Garrick Evans38b25a42020-04-06 15:17:42 +0900582 auto* dev = response.add_devices();
583 dev->set_ifname(config->tap_ifname());
584 dev->set_ipv4_addr(config->guest_ipv4_addr());
Garrick Evansa0c9c972020-11-30 09:54:59 +0900585 dev->set_guest_type(NetworkDevice::ARCVM);
Garrick Evans38b25a42020-04-06 15:17:42 +0900586 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900587
Garrick Evans08843932019-09-17 14:41:08 +0900588 writer.AppendProtoAsArrayOfBytes(response);
589 return dbus_response;
590}
591
592std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
593 dbus::MethodCall* method_call) {
594 LOG(INFO) << "ARCVM shutting down";
595
596 std::unique_ptr<dbus::Response> dbus_response(
597 dbus::Response::FromMethodCall(method_call));
598
599 dbus::MessageReader reader(method_call);
600 dbus::MessageWriter writer(dbus_response.get());
601
602 patchpanel::ArcVmShutdownRequest request;
603 patchpanel::ArcVmShutdownResponse response;
604
605 if (!reader.PopArrayOfBytesAsProto(&request)) {
606 LOG(ERROR) << "Unable to parse request";
607 writer.AppendProtoAsArrayOfBytes(response);
608 return dbus_response;
609 }
610
Garrick Evans21173b12019-11-20 15:23:16 +0900611 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900612
Garrick Evans08843932019-09-17 14:41:08 +0900613 writer.AppendProtoAsArrayOfBytes(response);
614 return dbus_response;
615}
616
Garrick Evans47c19272019-11-21 10:58:21 +0900617std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
618 dbus::MethodCall* method_call) {
619 LOG(INFO) << "Termina VM starting up";
620
621 std::unique_ptr<dbus::Response> dbus_response(
622 dbus::Response::FromMethodCall(method_call));
623
624 dbus::MessageReader reader(method_call);
625 dbus::MessageWriter writer(dbus_response.get());
626
627 patchpanel::TerminaVmStartupRequest request;
628 patchpanel::TerminaVmStartupResponse response;
629
630 if (!reader.PopArrayOfBytesAsProto(&request)) {
631 LOG(ERROR) << "Unable to parse request";
632 writer.AppendProtoAsArrayOfBytes(response);
633 return dbus_response;
634 }
635
636 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900637 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900638 LOG(ERROR) << "Failed to start Termina VM network service";
639 writer.AppendProtoAsArrayOfBytes(response);
640 return dbus_response;
641 }
642
Garrick Evans51d5b552020-01-30 10:42:06 +0900643 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900644 if (!tap) {
645 LOG(DFATAL) << "TAP device missing";
646 writer.AppendProtoAsArrayOfBytes(response);
647 return dbus_response;
648 }
Garrick Evans47c19272019-11-21 10:58:21 +0900649
Garrick Evansb1c93712020-01-22 09:28:25 +0900650 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900651 dev->set_ifname(tap->host_ifname());
Garrick Evansa0c9c972020-11-30 09:54:59 +0900652 dev->set_guest_type(NetworkDevice::TERMINA_VM);
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900653 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900654 if (!subnet) {
655 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
656 writer.AppendProtoAsArrayOfBytes(response);
657 return dbus_response;
658 }
659 auto* resp_subnet = dev->mutable_ipv4_subnet();
660 resp_subnet->set_base_addr(subnet->BaseAddress());
661 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900662 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900663 if (!subnet) {
664 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
665 writer.AppendProtoAsArrayOfBytes(response);
666 return dbus_response;
667 }
668 resp_subnet = response.mutable_container_subnet();
669 resp_subnet->set_base_addr(subnet->BaseAddress());
670 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900671
672 writer.AppendProtoAsArrayOfBytes(response);
673 return dbus_response;
674}
675
676std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
677 dbus::MethodCall* method_call) {
678 LOG(INFO) << "Termina VM shutting down";
679
680 std::unique_ptr<dbus::Response> dbus_response(
681 dbus::Response::FromMethodCall(method_call));
682
683 dbus::MessageReader reader(method_call);
684 dbus::MessageWriter writer(dbus_response.get());
685
686 patchpanel::TerminaVmShutdownRequest request;
687 patchpanel::TerminaVmShutdownResponse response;
688
689 if (!reader.PopArrayOfBytesAsProto(&request)) {
690 LOG(ERROR) << "Unable to parse request";
691 writer.AppendProtoAsArrayOfBytes(response);
692 return dbus_response;
693 }
694
Garrick Evans51d5b552020-01-30 10:42:06 +0900695 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
696
697 writer.AppendProtoAsArrayOfBytes(response);
698 return dbus_response;
699}
700
701std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
702 dbus::MethodCall* method_call) {
703 LOG(INFO) << "Plugin VM starting up";
704
705 std::unique_ptr<dbus::Response> dbus_response(
706 dbus::Response::FromMethodCall(method_call));
707
708 dbus::MessageReader reader(method_call);
709 dbus::MessageWriter writer(dbus_response.get());
710
711 patchpanel::PluginVmStartupRequest request;
712 patchpanel::PluginVmStartupResponse response;
713
714 if (!reader.PopArrayOfBytesAsProto(&request)) {
715 LOG(ERROR) << "Unable to parse request";
716 writer.AppendProtoAsArrayOfBytes(response);
717 return dbus_response;
718 }
719
Garrick Evans08fb34b2020-02-20 10:50:17 +0900720 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900721 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900722 LOG(ERROR) << "Failed to start Plugin VM network service";
723 writer.AppendProtoAsArrayOfBytes(response);
724 return dbus_response;
725 }
726
727 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
728 if (!tap) {
729 LOG(DFATAL) << "TAP device missing";
730 writer.AppendProtoAsArrayOfBytes(response);
731 return dbus_response;
732 }
733
Garrick Evans51d5b552020-01-30 10:42:06 +0900734 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900735 dev->set_ifname(tap->host_ifname());
Garrick Evansa0c9c972020-11-30 09:54:59 +0900736 dev->set_guest_type(NetworkDevice::PLUGIN_VM);
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900737 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900738 if (!subnet) {
739 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
740 writer.AppendProtoAsArrayOfBytes(response);
741 return dbus_response;
742 }
743 auto* resp_subnet = dev->mutable_ipv4_subnet();
744 resp_subnet->set_base_addr(subnet->BaseAddress());
745 resp_subnet->set_prefix_len(subnet->PrefixLength());
746
747 writer.AppendProtoAsArrayOfBytes(response);
748 return dbus_response;
749}
750
751std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
752 dbus::MethodCall* method_call) {
753 LOG(INFO) << "Plugin VM shutting down";
754
755 std::unique_ptr<dbus::Response> dbus_response(
756 dbus::Response::FromMethodCall(method_call));
757
758 dbus::MessageReader reader(method_call);
759 dbus::MessageWriter writer(dbus_response.get());
760
761 patchpanel::PluginVmShutdownRequest request;
762 patchpanel::PluginVmShutdownResponse response;
763
764 if (!reader.PopArrayOfBytesAsProto(&request)) {
765 LOG(ERROR) << "Unable to parse request";
766 writer.AppendProtoAsArrayOfBytes(response);
767 return dbus_response;
768 }
769
770 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900771
772 writer.AppendProtoAsArrayOfBytes(response);
773 return dbus_response;
774}
775
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900776std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
777 dbus::MethodCall* method_call) {
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::SetVpnIntentRequest request;
785 patchpanel::SetVpnIntentResponse response;
786
787 bool success = reader.PopArrayOfBytesAsProto(&request);
788 if (!success) {
789 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
790 // Do not return yet to make sure we close the received fd.
791 }
792
793 base::ScopedFD client_socket;
794 reader.PopFileDescriptor(&client_socket);
795
796 if (success)
797 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
798
799 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900800
801 writer.AppendProtoAsArrayOfBytes(response);
802 return dbus_response;
803}
804
805std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
806 dbus::MethodCall* method_call) {
807 std::unique_ptr<dbus::Response> dbus_response(
808 dbus::Response::FromMethodCall(method_call));
809
810 dbus::MessageReader reader(method_call);
811 dbus::MessageWriter writer(dbus_response.get());
812
813 patchpanel::ConnectNamespaceRequest request;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900814
815 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900816 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
817 // Do not return yet to make sure we close the received fd and
818 // validate other arguments.
Hugo Benichi7c342672020-09-08 09:18:14 +0900819 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
820 return dbus_response;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900821 }
822
Hugo Benichicc6850f2020-01-17 13:26:06 +0900823 base::ScopedFD client_fd;
824 reader.PopFileDescriptor(&client_fd);
825 if (!client_fd.is_valid()) {
826 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
Hugo Benichi7c342672020-09-08 09:18:14 +0900827 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
828 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900829 }
830
831 pid_t pid = request.pid();
Garrick Evans263bd952020-12-03 20:27:43 +0900832 if (pid == 1 || pid == getpid()) {
833 LOG(ERROR) << "ConnectNamespaceRequest: privileged namespace pid " << pid;
834 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
835 return dbus_response;
836 }
Hugo Benichicc6850f2020-01-17 13:26:06 +0900837 {
838 ScopedNS ns(pid);
839 if (!ns.IsValid()) {
840 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900841 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
842 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900843 }
844 }
845
846 const std::string& outbound_ifname = request.outbound_physical_device();
847 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
848 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
849 << outbound_ifname;
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
Hugo Benichi7c342672020-09-08 09:18:14 +0900854 auto response = ConnectNamespace(std::move(client_fd), request);
855 writer.AppendProtoAsArrayOfBytes(*response);
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900856 return dbus_response;
857}
858
Jie Jiang493cde42020-07-17 21:43:39 +0900859std::unique_ptr<dbus::Response> Manager::OnGetTrafficCounters(
860 dbus::MethodCall* method_call) {
861 std::unique_ptr<dbus::Response> dbus_response(
862 dbus::Response::FromMethodCall(method_call));
863
864 dbus::MessageReader reader(method_call);
865 dbus::MessageWriter writer(dbus_response.get());
866
867 patchpanel::TrafficCountersRequest request;
868 patchpanel::TrafficCountersResponse response;
869
870 if (!reader.PopArrayOfBytesAsProto(&request)) {
871 LOG(ERROR) << "Unable to parse TrafficCountersRequest";
872 writer.AppendProtoAsArrayOfBytes(response);
873 return dbus_response;
874 }
875
876 const std::set<std::string> devices{request.devices().begin(),
877 request.devices().end()};
Hugo Benichi1df64172020-12-13 22:59:01 +0900878 // TODO(b/175364240) Find why iptables -L -x -v -w can freeze on
879 // writing to stdout and in turn block patchpanel.
880 /*
Jie Jiang493cde42020-07-17 21:43:39 +0900881 const auto counters = counters_svc_->GetCounters(devices);
882 for (const auto& kv : counters) {
883 auto* traffic_counter = response.add_counters();
884 const auto& source_and_device = kv.first;
885 const auto& counter = kv.second;
886 traffic_counter->set_source(source_and_device.first);
887 traffic_counter->set_device(source_and_device.second);
888 traffic_counter->set_rx_bytes(counter.rx_bytes);
889 traffic_counter->set_rx_packets(counter.rx_packets);
890 traffic_counter->set_tx_bytes(counter.tx_bytes);
891 traffic_counter->set_tx_packets(counter.tx_packets);
892 }
Hugo Benichi1df64172020-12-13 22:59:01 +0900893 */
Jie Jiang493cde42020-07-17 21:43:39 +0900894
895 writer.AppendProtoAsArrayOfBytes(response);
896 return dbus_response;
897}
898
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900899std::unique_ptr<dbus::Response> Manager::OnModifyPortRule(
900 dbus::MethodCall* method_call) {
901 std::unique_ptr<dbus::Response> dbus_response(
902 dbus::Response::FromMethodCall(method_call));
903
904 dbus::MessageReader reader(method_call);
905 dbus::MessageWriter writer(dbus_response.get());
906
907 patchpanel::ModifyPortRuleRequest request;
908 patchpanel::ModifyPortRuleResponse response;
909
910 if (!reader.PopArrayOfBytesAsProto(&request)) {
911 LOG(ERROR) << "Unable to parse ModifyPortRequest";
912 writer.AppendProtoAsArrayOfBytes(response);
913 return dbus_response;
914 }
915
Jason Jeremy Imanc28df852020-07-11 17:38:26 +0900916 response.set_success(ModifyPortRule(request));
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900917 writer.AppendProtoAsArrayOfBytes(response);
918 return dbus_response;
919}
920
Jie Jiang25c1b972020-11-12 15:42:53 +0900921void Manager::OnNeighborReachabilityEvent(
Jie Jiang84966852020-09-18 18:49:05 +0900922 int ifindex,
923 const shill::IPAddress& ip_addr,
924 NeighborLinkMonitor::NeighborRole role,
Jie Jiang25c1b972020-11-12 15:42:53 +0900925 NeighborReachabilityEventSignal::EventType event_type) {
Jie Jiang84966852020-09-18 18:49:05 +0900926 if (!ip_addr.IsValid()) {
927 LOG(DFATAL) << "ip_addr is not valid";
928 return;
929 }
930
Jie Jiang25c1b972020-11-12 15:42:53 +0900931 using SignalProto = NeighborReachabilityEventSignal;
Jie Jiang84966852020-09-18 18:49:05 +0900932 SignalProto proto;
933 proto.set_ifindex(ifindex);
934 proto.set_ip_addr(ip_addr.ToString());
Jie Jiang25c1b972020-11-12 15:42:53 +0900935 proto.set_type(event_type);
Jie Jiang84966852020-09-18 18:49:05 +0900936 switch (role) {
937 case NeighborLinkMonitor::NeighborRole::kGateway:
938 proto.set_role(SignalProto::GATEWAY);
939 break;
940 case NeighborLinkMonitor::NeighborRole::kDNSServer:
941 proto.set_role(SignalProto::DNS_SERVER);
942 break;
943 case NeighborLinkMonitor::NeighborRole::kGatewayAndDNSServer:
944 proto.set_role(SignalProto::GATEWAY_AND_DNS_SERVER);
945 break;
946 default:
947 NOTREACHED();
948 }
949
Jie Jiang25c1b972020-11-12 15:42:53 +0900950 dbus::Signal signal(kPatchPanelInterface, kNeighborReachabilityEventSignal);
Jie Jiang84966852020-09-18 18:49:05 +0900951 dbus::MessageWriter writer(&signal);
952 if (!writer.AppendProtoAsArrayOfBytes(proto)) {
Jie Jiang25c1b972020-11-12 15:42:53 +0900953 LOG(ERROR) << "Failed to encode proto NeighborReachabilityEventSignal";
Jie Jiang84966852020-09-18 18:49:05 +0900954 return;
955 }
956
957 dbus_svc_path_->SendSignal(&signal);
958}
959
Hugo Benichi7c342672020-09-08 09:18:14 +0900960std::unique_ptr<patchpanel::ConnectNamespaceResponse> Manager::ConnectNamespace(
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900961 base::ScopedFD client_fd,
Hugo Benichi7c342672020-09-08 09:18:14 +0900962 const patchpanel::ConnectNamespaceRequest& request) {
963 auto response = std::make_unique<patchpanel::ConnectNamespaceResponse>();
964
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900965 std::unique_ptr<Subnet> subnet =
966 addr_mgr_.AllocateIPv4Subnet(AddressManager::Guest::MINIJAIL_NETNS);
967 if (!subnet) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900968 LOG(ERROR) << "ConnectNamespace: exhausted IPv4 subnet space";
969 return response;
Hugo Benichie8758b52020-04-03 14:49:01 +0900970 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900971
Hugo Benichi7352ad92020-04-07 16:11:59 +0900972 // Dup the client fd into our own: this guarantees that the fd number will
973 // be stable and tied to the actual kernel resources used by the client.
974 base::ScopedFD local_client_fd(dup(client_fd.get()));
975 if (!local_client_fd.is_valid()) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900976 PLOG(ERROR) << "ConnectNamespace: failed to dup() client fd";
977 return response;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900978 }
979
Hugo Benichi7c342672020-09-08 09:18:14 +0900980 // Add the duped fd to the epoll watcher.
Hugo Benichi7352ad92020-04-07 16:11:59 +0900981 // TODO(hugobenichi) Find a way to reuse base::FileDescriptorWatcher for
982 // listening to EPOLLHUP.
983 struct epoll_event epevent;
984 epevent.events = EPOLLIN; // EPOLLERR | EPOLLHUP are always waited for.
985 epevent.data.fd = local_client_fd.get();
986 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_ADD,
987 local_client_fd.get(), &epevent) != 0) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900988 PLOG(ERROR) << "ConnectNamespace: epoll_ctl(EPOLL_CTL_ADD) failed";
989 return response;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900990 }
991
Hugo Benichi7c342672020-09-08 09:18:14 +0900992 const std::string ifname_id = std::to_string(connected_namespaces_next_id_);
Hugo Benichifcf81022020-12-04 11:01:37 +0900993 ConnectedNamespace nsinfo = {};
994 nsinfo.pid = request.pid();
995 nsinfo.netns_name = "connected_netns_" + ifname_id;
Hugo Benichi93306e52020-12-04 16:08:00 +0900996 nsinfo.source = ProtoToTrafficSource(request.traffic_source());
997 if (nsinfo.source == TrafficSource::UNKNOWN)
998 nsinfo.source = TrafficSource::SYSTEM;
Hugo Benichifcf81022020-12-04 11:01:37 +0900999 nsinfo.outbound_ifname = request.outbound_physical_device();
Hugo Benichi93306e52020-12-04 16:08:00 +09001000 nsinfo.route_on_vpn = request.route_on_vpn();
Hugo Benichifcf81022020-12-04 11:01:37 +09001001 nsinfo.host_ifname = "arc_ns" + ifname_id;
1002 nsinfo.peer_ifname = "veth" + ifname_id;
1003 nsinfo.peer_subnet = std::move(subnet);
1004 nsinfo.peer_mac_addr = addr_mgr_.GenerateMacAddress();
1005
1006 if (!datapath_->StartRoutingNamespace(nsinfo)) {
Hugo Benichi7c342672020-09-08 09:18:14 +09001007 LOG(ERROR) << "ConnectNamespace: failed to setup datapath";
1008 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL,
1009 local_client_fd.get(), nullptr) != 0)
1010 PLOG(ERROR) << "ConnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
1011 return response;
1012 }
1013
Hugo Benichifcf81022020-12-04 11:01:37 +09001014 // Prepare the response before storing ConnectedNamespace.
1015 response->set_peer_ifname(nsinfo.peer_ifname);
1016 response->set_peer_ipv4_address(nsinfo.peer_subnet->AddressAtOffset(1));
1017 response->set_host_ifname(nsinfo.host_ifname);
1018 response->set_host_ipv4_address(nsinfo.peer_subnet->AddressAtOffset(0));
Hugo Benichi7c342672020-09-08 09:18:14 +09001019 auto* response_subnet = response->mutable_ipv4_subnet();
Hugo Benichifcf81022020-12-04 11:01:37 +09001020 response_subnet->set_base_addr(nsinfo.peer_subnet->BaseAddress());
1021 response_subnet->set_prefix_len(nsinfo.peer_subnet->PrefixLength());
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001022
Hugo Benichifcf81022020-12-04 11:01:37 +09001023 LOG(INFO) << "Connected network namespace " << nsinfo;
1024
1025 // Store ConnectedNamespace
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001026 connected_namespaces_next_id_++;
Hugo Benichi7352ad92020-04-07 16:11:59 +09001027 int fdkey = local_client_fd.release();
Hugo Benichifcf81022020-12-04 11:01:37 +09001028 connected_namespaces_.insert(std::make_pair(fdkey, std::move(nsinfo)));
Hugo Benichi7352ad92020-04-07 16:11:59 +09001029
1030 if (connected_namespaces_.size() == 1) {
1031 LOG(INFO) << "Starting ConnectNamespace client fds monitoring";
1032 CheckConnectedNamespaces();
1033 }
Hugo Benichi7c342672020-09-08 09:18:14 +09001034
1035 return response;
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001036}
1037
1038void Manager::DisconnectNamespace(int client_fd) {
1039 auto it = connected_namespaces_.find(client_fd);
1040 if (it == connected_namespaces_.end()) {
Hugo Benichifcf81022020-12-04 11:01:37 +09001041 LOG(ERROR) << "No ConnectedNamespace found for client_fd " << client_fd;
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001042 return;
1043 }
1044
Hugo Benichi7352ad92020-04-07 16:11:59 +09001045 // Remove the client fd dupe from the epoll watcher and close it.
1046 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL, client_fd,
Hugo Benichie8758b52020-04-03 14:49:01 +09001047 nullptr) != 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +09001048 PLOG(ERROR) << "DisconnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +09001049 if (close(client_fd) < 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +09001050 PLOG(ERROR) << "DisconnectNamespace: close(client_fd) failed";
Hugo Benichi7352ad92020-04-07 16:11:59 +09001051
Hugo Benichifcf81022020-12-04 11:01:37 +09001052 datapath_->StopRoutingNamespace(it->second);
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001053 LOG(INFO) << "Disconnected network namespace " << it->second;
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001054 // This release the allocated IPv4 subnet.
1055 connected_namespaces_.erase(it);
1056}
1057
Hugo Benichi7352ad92020-04-07 16:11:59 +09001058// TODO(hugobenichi) Generalize this check to all resources created by
1059// patchpanel on behalf of a remote client.
1060void Manager::CheckConnectedNamespaces() {
1061 int max_event = 10;
1062 struct epoll_event epevents[max_event];
1063 int nready = epoll_wait(connected_namespaces_epollfd_, epevents, max_event,
1064 0 /* do not block */);
1065 if (nready < 0)
1066 PLOG(ERROR) << "CheckConnectedNamespaces: epoll_wait(0) failed";
1067
1068 for (int i = 0; i < nready; i++)
1069 if (epevents[i].events & (EPOLLHUP | EPOLLERR))
1070 DisconnectNamespace(epevents[i].data.fd);
1071
1072 if (connected_namespaces_.empty()) {
1073 LOG(INFO) << "Stopping ConnectNamespace client fds monitoring";
1074 return;
1075 }
1076
Qijiang Fan2d7aeb42020-05-19 02:06:39 +09001077 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Hugo Benichi7352ad92020-04-07 16:11:59 +09001078 FROM_HERE,
1079 base::Bind(&Manager::CheckConnectedNamespaces,
Hugo Benichie8758b52020-04-03 14:49:01 +09001080 weak_factory_.GetWeakPtr()),
Hugo Benichi7352ad92020-04-07 16:11:59 +09001081 kConnectNamespaceCheckInterval);
1082}
1083
Jason Jeremy Imanc28df852020-07-11 17:38:26 +09001084bool Manager::ModifyPortRule(const patchpanel::ModifyPortRuleRequest& request) {
1085 switch (request.proto()) {
1086 case patchpanel::ModifyPortRuleRequest::TCP:
1087 case patchpanel::ModifyPortRuleRequest::UDP:
1088 break;
1089 default:
1090 LOG(ERROR) << "Unknown protocol " << request.proto();
1091 return false;
1092 }
1093
1094 switch (request.op()) {
1095 case patchpanel::ModifyPortRuleRequest::CREATE:
1096 switch (request.type()) {
1097 case patchpanel::ModifyPortRuleRequest::ACCESS:
1098 return firewall_.AddAcceptRules(request.proto(),
1099 request.input_dst_port(),
1100 request.input_ifname());
1101 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
1102 return firewall_.AddLoopbackLockdownRules(request.proto(),
1103 request.input_dst_port());
1104 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1105 return firewall_.AddIpv4ForwardRule(
1106 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1107 request.input_ifname(), request.dst_ip(), request.dst_port());
1108 default:
1109 LOG(ERROR) << "Unknown port rule type " << request.type();
1110 return false;
1111 }
1112 case patchpanel::ModifyPortRuleRequest::DELETE:
1113 switch (request.type()) {
1114 case patchpanel::ModifyPortRuleRequest::ACCESS:
1115 return firewall_.DeleteAcceptRules(request.proto(),
1116 request.input_dst_port(),
1117 request.input_ifname());
1118 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
1119 return firewall_.DeleteLoopbackLockdownRules(
1120 request.proto(), request.input_dst_port());
1121 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1122 return firewall_.DeleteIpv4ForwardRule(
1123 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1124 request.input_ifname(), request.dst_ip(), request.dst_port());
1125 default:
1126 LOG(ERROR) << "Unknown port rule type " << request.type();
1127 return false;
1128 }
1129 default:
1130 LOG(ERROR) << "Unknown operation " << request.op();
1131 return false;
1132 }
1133}
1134
Garrick Evanse94a14e2019-11-11 10:32:13 +09001135void Manager::SendGuestMessage(const GuestMessage& msg) {
Garrick Evans96e03042019-05-28 14:30:52 +09001136 IpHelperMessage ipm;
1137 *ipm.mutable_guest_message() = msg;
Garrick Evans96e03042019-05-28 14:30:52 +09001138 adb_proxy_->SendMessage(ipm);
Garrick Evanse94a14e2019-11-11 10:32:13 +09001139 mcast_proxy_->SendMessage(ipm);
1140 nd_proxy_->SendMessage(ipm);
Garrick Evans96e03042019-05-28 14:30:52 +09001141}
1142
Garrick Evans4ac09852020-01-16 14:09:22 +09001143void Manager::StartForwarding(const std::string& ifname_physical,
1144 const std::string& ifname_virtual,
Garrick Evans4ac09852020-01-16 14:09:22 +09001145 bool ipv6,
1146 bool multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001147 if (ifname_physical.empty() || ifname_virtual.empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001148 return;
1149
1150 IpHelperMessage ipm;
1151 DeviceMessage* msg = ipm.mutable_device_message();
1152 msg->set_dev_ifname(ifname_physical);
Garrick Evans4ac09852020-01-16 14:09:22 +09001153 msg->set_br_ifname(ifname_virtual);
1154
1155 if (ipv6) {
1156 LOG(INFO) << "Starting IPv6 forwarding from " << ifname_physical << " to "
1157 << ifname_virtual;
1158
1159 if (!datapath_->AddIPv6Forwarding(ifname_physical, ifname_virtual)) {
1160 LOG(ERROR) << "Failed to setup iptables forwarding rule for IPv6 from "
1161 << ifname_physical << " to " << ifname_virtual;
1162 }
1163 if (!datapath_->MaskInterfaceFlags(ifname_physical, IFF_ALLMULTI)) {
1164 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1165 << ifname_physical;
1166 }
1167 if (!datapath_->MaskInterfaceFlags(ifname_virtual, IFF_ALLMULTI)) {
1168 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1169 << ifname_virtual;
1170 }
1171 nd_proxy_->SendMessage(ipm);
1172 }
1173
1174 if (multicast) {
1175 LOG(INFO) << "Starting multicast forwarding from " << ifname_physical
1176 << " to " << ifname_virtual;
1177 mcast_proxy_->SendMessage(ipm);
1178 }
1179}
1180
1181void Manager::StopForwarding(const std::string& ifname_physical,
1182 const std::string& ifname_virtual,
1183 bool ipv6,
1184 bool multicast) {
1185 if (ifname_physical.empty())
1186 return;
1187
1188 IpHelperMessage ipm;
1189 DeviceMessage* msg = ipm.mutable_device_message();
1190 msg->set_dev_ifname(ifname_physical);
1191 msg->set_teardown(true);
Taoyu Li7dca19a2020-03-16 16:27:07 +09001192 if (!ifname_virtual.empty()) {
1193 msg->set_br_ifname(ifname_virtual);
1194 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001195
1196 if (ipv6) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001197 if (ifname_virtual.empty()) {
1198 LOG(INFO) << "Stopping IPv6 forwarding on " << ifname_physical;
1199 } else {
1200 LOG(INFO) << "Stopping IPv6 forwarding from " << ifname_physical << " to "
1201 << ifname_virtual;
1202 datapath_->RemoveIPv6Forwarding(ifname_physical, ifname_virtual);
1203 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001204 nd_proxy_->SendMessage(ipm);
1205 }
1206
1207 if (multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001208 if (ifname_virtual.empty()) {
1209 LOG(INFO) << "Stopping multicast forwarding on " << ifname_physical;
1210 } else {
1211 LOG(INFO) << "Stopping multicast forwarding from " << ifname_physical
1212 << " to " << ifname_virtual;
1213 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001214 mcast_proxy_->SendMessage(ipm);
1215 }
1216}
1217
Taoyu Lia0727dc2020-09-24 19:54:59 +09001218void Manager::OnNDProxyMessage(const NDProxyMessage& msg) {
1219 LOG_IF(DFATAL, msg.ifname().empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001220 << "Received DeviceMessage w/ empty dev_ifname";
Taoyu Lia0727dc2020-09-24 19:54:59 +09001221 switch (msg.type()) {
1222 case NDProxyMessage::ADD_ROUTE:
1223 if (!datapath_->AddIPv6HostRoute(msg.ifname(), msg.ip6addr(), 128)) {
1224 LOG(WARNING) << "Failed to setup the IPv6 route for interface "
1225 << msg.ifname() << ", addr " << msg.ip6addr();
1226 }
1227 break;
1228 case NDProxyMessage::ADD_ADDR:
1229 if (!datapath_->AddIPv6Address(msg.ifname(), msg.ip6addr())) {
1230 LOG(WARNING) << "Failed to setup the IPv6 address for interface "
1231 << msg.ifname() << ", addr " << msg.ip6addr();
1232 }
1233 break;
1234 case NDProxyMessage::DEL_ADDR:
1235 datapath_->RemoveIPv6Address(msg.ifname(), msg.ip6addr());
1236 break;
1237 default:
1238 LOG(ERROR) << "Unknown NDProxy event " << msg.type();
1239 NOTREACHED();
Garrick Evans4ac09852020-01-16 14:09:22 +09001240 }
1241}
1242
Garrick Evans3388a032020-03-24 11:25:55 +09001243} // namespace patchpanel