blob: d0e47b8b1bc870a0af076239899eeda3620d4c31 [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 Benichi7d9d8db2020-03-30 15:56:56 +090018#include "base/files/scoped_file.h"
Hugo Benichicc6850f2020-01-17 13:26:06 +090019#include <base/bind.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
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +090039constexpr char kNDProxyFeatureName[] = "ARC NDProxy";
40constexpr int kNDProxyMinAndroidSdkVersion = 28; // P
41constexpr int kNDProxyMinChromeMilestone = 80;
Taoyu Lic85c44b2019-12-04 17:32:57 +090042
Hugo Benichi7352ad92020-04-07 16:11:59 +090043// Time interval between epoll checks on file descriptors committed by callers
44// of ConnectNamespace DBus API.
45constexpr const base::TimeDelta kConnectNamespaceCheckInterval =
Hugo Benichifa9462e2020-06-26 09:50:48 +090046 base::TimeDelta::FromSeconds(5);
Hugo Benichi7352ad92020-04-07 16:11:59 +090047
Garrick Evans08843932019-09-17 14:41:08 +090048// Passes |method_call| to |handler| and passes the response to
49// |response_sender|. If |handler| returns nullptr, an empty response is
50// created and sent.
51void HandleSynchronousDBusMethodCall(
52 base::Callback<std::unique_ptr<dbus::Response>(dbus::MethodCall*)> handler,
53 dbus::MethodCall* method_call,
54 dbus::ExportedObject::ResponseSender response_sender) {
55 std::unique_ptr<dbus::Response> response = handler.Run(method_call);
56 if (!response)
57 response = dbus::Response::FromMethodCall(method_call);
58 response_sender.Run(std::move(response));
59}
60
61} // namespace
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070062
Taoyu Lice7caa62019-10-01 15:43:33 +090063Manager::Manager(std::unique_ptr<HelperProcess> adb_proxy,
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090064 std::unique_ptr<HelperProcess> mcast_proxy,
Garrick Evans1f5a3612019-11-08 12:59:03 +090065 std::unique_ptr<HelperProcess> nd_proxy)
Garrick Evans3915af32019-07-25 15:44:34 +090066 : adb_proxy_(std::move(adb_proxy)),
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090067 mcast_proxy_(std::move(mcast_proxy)),
Garrick Evans4ee5ce22020-03-18 07:05:17 +090068 nd_proxy_(std::move(nd_proxy)) {
Taoyu Li179dcc62019-10-17 11:21:08 +090069 runner_ = std::make_unique<MinijailedProcessRunner>();
70 datapath_ = std::make_unique<Datapath>(runner_.get());
Hugo Benichi7352ad92020-04-07 16:11:59 +090071 connected_namespaces_epollfd_ = epoll_create(1 /* size */);
Taoyu Li179dcc62019-10-17 11:21:08 +090072}
Long Chengd4415582019-09-24 19:16:09 +000073
Garrick Evans207e7482019-12-16 11:54:36 +090074Manager::~Manager() {
75 OnShutdown(nullptr);
76}
77
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +090078std::map<const std::string, bool> Manager::cached_feature_enabled_ = {};
79
80bool Manager::ShouldEnableFeature(
81 int min_android_sdk_version,
82 int min_chrome_milestone,
83 const std::vector<std::string>& supported_boards,
84 const std::string& feature_name) {
85 static const char kLsbReleasePath[] = "/etc/lsb-release";
86
87 const auto& cached_result = cached_feature_enabled_.find(feature_name);
88 if (cached_result != cached_feature_enabled_.end())
89 return cached_result->second;
90
91 auto check = [min_android_sdk_version, min_chrome_milestone,
92 &supported_boards, &feature_name]() {
93 brillo::KeyValueStore store;
94 if (!store.Load(base::FilePath(kLsbReleasePath))) {
95 LOG(ERROR) << "Could not read lsb-release";
96 return false;
97 }
98
99 std::string value;
100 if (!store.GetString("CHROMEOS_ARC_ANDROID_SDK_VERSION", &value)) {
101 LOG(ERROR) << feature_name
102 << " disabled - cannot determine Android SDK version";
103 return false;
104 }
105 int ver = 0;
106 if (!base::StringToInt(value.c_str(), &ver)) {
107 LOG(ERROR) << feature_name << " disabled - invalid Android SDK version";
108 return false;
109 }
110 if (ver < min_android_sdk_version) {
111 LOG(INFO) << feature_name << " disabled for Android SDK " << value;
112 return false;
113 }
114
115 if (!store.GetString("CHROMEOS_RELEASE_CHROME_MILESTONE", &value)) {
116 LOG(ERROR) << feature_name
117 << " disabled - cannot determine ChromeOS milestone";
118 return false;
119 }
120 if (!base::StringToInt(value.c_str(), &ver)) {
121 LOG(ERROR) << feature_name << " disabled - invalid ChromeOS milestone";
122 return false;
123 }
124 if (ver < min_chrome_milestone) {
125 LOG(INFO) << feature_name << " disabled for ChromeOS milestone " << value;
126 return false;
127 }
128
129 if (!store.GetString("CHROMEOS_RELEASE_BOARD", &value)) {
130 LOG(ERROR) << feature_name << " disabled - cannot determine board";
131 return false;
132 }
133 if (!supported_boards.empty() &&
134 std::find(supported_boards.begin(), supported_boards.end(), value) ==
135 supported_boards.end()) {
136 LOG(INFO) << feature_name << " disabled for board " << value;
137 return false;
138 }
139 return true;
140 };
141
142 bool result = check();
143 cached_feature_enabled_.emplace(feature_name, result);
144 return result;
145}
146
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700147int Manager::OnInit() {
Garrick Evans54861622019-07-19 09:05:09 +0900148 prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800149
150 // Handle subprocess lifecycle.
151 process_reaper_.Register(this);
Hugo Benichi935eca92018-07-03 13:47:24 +0900152
153 CHECK(process_reaper_.WatchForChild(
Garrick Evans96e03042019-05-28 14:30:52 +0900154 FROM_HERE, adb_proxy_->pid(),
155 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
156 adb_proxy_->pid())))
157 << "Failed to watch adb-proxy child process";
Taoyu Liaf944c92019-10-01 12:22:31 +0900158 CHECK(process_reaper_.WatchForChild(
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900159 FROM_HERE, mcast_proxy_->pid(),
160 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
161 nd_proxy_->pid())))
162 << "Failed to watch multicast-proxy child process";
163 CHECK(process_reaper_.WatchForChild(
Taoyu Liaf944c92019-10-01 12:22:31 +0900164 FROM_HERE, nd_proxy_->pid(),
165 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
166 nd_proxy_->pid())))
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900167 << "Failed to watch nd-proxy child process";
Garrick Evans96e03042019-05-28 14:30:52 +0900168
Garrick Evans49879532018-12-03 13:15:36 +0900169 // Run after Daemon::OnInit().
hschamf9546312020-04-14 15:12:40 +0900170 base::ThreadTaskRunnerHandle::Get()->PostTask(
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700171 FROM_HERE,
172 base::Bind(&Manager::InitialSetup, weak_factory_.GetWeakPtr()));
173
174 return DBusDaemon::OnInit();
175}
176
177void Manager::InitialSetup() {
Garrick Evans08843932019-09-17 14:41:08 +0900178 LOG(INFO) << "Setting up DBus service interface";
179 dbus_svc_path_ = bus_->GetExportedObject(
180 dbus::ObjectPath(patchpanel::kPatchPanelServicePath));
181 if (!dbus_svc_path_) {
182 LOG(FATAL) << "Failed to export " << patchpanel::kPatchPanelServicePath
183 << " object";
184 }
185
186 using ServiceMethod =
187 std::unique_ptr<dbus::Response> (Manager::*)(dbus::MethodCall*);
188 const std::map<const char*, ServiceMethod> kServiceMethods = {
189 {patchpanel::kArcStartupMethod, &Manager::OnArcStartup},
190 {patchpanel::kArcShutdownMethod, &Manager::OnArcShutdown},
191 {patchpanel::kArcVmStartupMethod, &Manager::OnArcVmStartup},
192 {patchpanel::kArcVmShutdownMethod, &Manager::OnArcVmShutdown},
Garrick Evans47c19272019-11-21 10:58:21 +0900193 {patchpanel::kTerminaVmStartupMethod, &Manager::OnTerminaVmStartup},
194 {patchpanel::kTerminaVmShutdownMethod, &Manager::OnTerminaVmShutdown},
Garrick Evans51d5b552020-01-30 10:42:06 +0900195 {patchpanel::kPluginVmStartupMethod, &Manager::OnPluginVmStartup},
196 {patchpanel::kPluginVmShutdownMethod, &Manager::OnPluginVmShutdown},
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900197 {patchpanel::kSetVpnIntentMethod, &Manager::OnSetVpnIntent},
Hugo Benichib56b77c2020-01-15 16:00:56 +0900198 {patchpanel::kConnectNamespaceMethod, &Manager::OnConnectNamespace},
Garrick Evans08843932019-09-17 14:41:08 +0900199 };
200
201 for (const auto& kv : kServiceMethods) {
202 if (!dbus_svc_path_->ExportMethodAndBlock(
203 patchpanel::kPatchPanelInterface, kv.first,
204 base::Bind(&HandleSynchronousDBusMethodCall,
205 base::Bind(kv.second, base::Unretained(this))))) {
206 LOG(FATAL) << "Failed to export method " << kv.first;
207 }
208 }
209
210 if (!bus_->RequestOwnershipAndBlock(patchpanel::kPatchPanelServiceName,
211 dbus::Bus::REQUIRE_PRIMARY)) {
212 LOG(FATAL) << "Failed to take ownership of "
213 << patchpanel::kPatchPanelServiceName;
214 }
215 LOG(INFO) << "DBus service interface ready";
216
Taoyu Li6d479442019-12-09 13:02:29 +0900217 auto& runner = datapath_->runner();
Garrick Evans7cf8c542020-05-25 09:50:17 +0900218 // Enable IPv4 packet forwarding
219 if (runner.sysctl_w("net.ipv4.ip_forward", "1") != 0) {
220 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
221 << " Guest connectivity will not work correctly.";
222 }
Garrick Evans28d194e2019-12-17 10:22:28 +0900223 // Limit local port range: Android owns 47104-61000.
224 // TODO(garrick): The original history behind this tweak is gone. Some
225 // investigation is needed to see if it is still applicable.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900226 if (runner.sysctl_w("net.ipv4.ip_local_port_range", "32768 47103") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900227 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
228 << " apps may not work correctly.";
229 }
Taoyu Li6d479442019-12-09 13:02:29 +0900230 // Enable IPv6 packet forarding
Garrick Evans8e8e3472020-01-23 14:03:50 +0900231 if (runner.sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0) {
Taoyu Li6d479442019-12-09 13:02:29 +0900232 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
233 << " IPv6 functionality may be broken.";
234 }
235 // Kernel proxy_ndp is only needed for legacy IPv6 configuration
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +0900236 if (!ShouldEnableFeature(kNDProxyMinAndroidSdkVersion,
Garrick Evansf5862122020-03-16 09:13:45 +0900237 kNDProxyMinChromeMilestone, {},
238 kNDProxyFeatureName) &&
Garrick Evans8e8e3472020-01-23 14:03:50 +0900239 runner.sysctl_w("net.ipv6.conf.all.proxy_ndp", "1") != 0) {
Taoyu Li6d479442019-12-09 13:02:29 +0900240 LOG(ERROR) << "Failed to update net.ipv6.conf.all.proxy_ndp."
241 << " IPv6 functionality may be broken.";
242 }
243
Garrick Evansd291af62020-05-25 10:39:06 +0900244 if (!datapath_->AddSNATMarkRules()) {
245 LOG(ERROR) << "Failed to install SNAT mark rules."
246 << " Guest connectivity may be broken.";
247 }
248 if (!datapath_->AddForwardEstablishedRule()) {
249 LOG(ERROR) << "Failed to install forwarding rule for established"
250 << " connections.";
251 }
252
Garrick Evansff6e37f2020-05-25 10:54:47 +0900253 // TODO(chromium:898210): Move interface-specific masquerading setup to shill;
254 // such that we can better set up the masquerade rules based on connection
255 // type rather than interface names.
256 if (!datapath_->AddInterfaceSNAT("wwan+")) {
257 LOG(ERROR) << "Failed to set up wifi masquerade";
258 }
259
Garrick Evansc50426b2020-05-25 11:00:55 +0900260 if (!datapath_->AddOutboundIPv4SNATMark("vmtap+")) {
261 LOG(ERROR) << "Failed to set up NAT for TAP devices."
262 << " Guest connectivity may be broken.";
263 }
264
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900265 routing_svc_ = std::make_unique<RoutingService>();
266
Garrick Evans4ac09852020-01-16 14:09:22 +0900267 nd_proxy_->RegisterDeviceMessageHandler(base::Bind(
268 &Manager::OnDeviceMessageFromNDProxy, weak_factory_.GetWeakPtr()));
269
Garrick Evans69b85872020-02-04 11:40:26 +0900270 shill_client_ = std::make_unique<ShillClient>(bus_);
Garrick Evans1b1f67c2020-02-04 16:21:25 +0900271 auto* const forwarder = static_cast<TrafficForwarder*>(this);
Garrick Evans5d55f5e2019-07-17 15:28:10 +0900272
Hugo Benichiad1bdd92020-06-12 13:48:37 +0900273 GuestMessage::GuestType arc_guest =
274 USE_ARCVM ? GuestMessage::ARC_VM : GuestMessage::ARC;
275 arc_svc_ = std::make_unique<ArcService>(shill_client_.get(), datapath_.get(),
276 &addr_mgr_, forwarder, arc_guest);
Garrick Evans1b1f67c2020-02-04 16:21:25 +0900277 cros_svc_ = std::make_unique<CrostiniService>(shill_client_.get(), &addr_mgr_,
278 datapath_.get(), forwarder);
Jie Jiang01c1a2e2020-04-08 20:58:30 +0900279 network_monitor_svc_ =
280 std::make_unique<NetworkMonitorService>(shill_client_.get());
281 network_monitor_svc_->Start();
Taoyu Liaf944c92019-10-01 12:22:31 +0900282
283 nd_proxy_->Listen();
Long Chengd4415582019-09-24 19:16:09 +0000284}
Garrick Evans49879532018-12-03 13:15:36 +0900285
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800286void Manager::OnShutdown(int* exit_code) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900287 LOG(INFO) << "Shutting down and cleaning up";
Garrick Evans207e7482019-12-16 11:54:36 +0900288 cros_svc_.reset();
289 arc_svc_.reset();
Hugo Benichi7352ad92020-04-07 16:11:59 +0900290 close(connected_namespaces_epollfd_);
Hugo Benichie8758b52020-04-03 14:49:01 +0900291 // Tear down any remaining connected namespace.
292 std::vector<int> connected_namespaces_fdkeys;
293 for (const auto& kv : connected_namespaces_)
294 connected_namespaces_fdkeys.push_back(kv.first);
295 for (const int fdkey : connected_namespaces_fdkeys)
296 DisconnectNamespace(fdkey);
Garrick Evans28d194e2019-12-17 10:22:28 +0900297
Garrick Evansc50426b2020-05-25 11:00:55 +0900298 datapath_->RemoveOutboundIPv4SNATMark("vmtap+");
Garrick Evansff6e37f2020-05-25 10:54:47 +0900299 datapath_->RemoveInterfaceSNAT("wwan+");
Garrick Evansd291af62020-05-25 10:39:06 +0900300 datapath_->RemoveForwardEstablishedRule();
301 datapath_->RemoveSNATMarkRules();
302
Garrick Evans7cf8c542020-05-25 09:50:17 +0900303 auto& runner = datapath_->runner();
Garrick Evans28d194e2019-12-17 10:22:28 +0900304 // Restore original local port range.
305 // TODO(garrick): The original history behind this tweak is gone. Some
306 // investigation is needed to see if it is still applicable.
Garrick Evans7cf8c542020-05-25 09:50:17 +0900307 if (runner.sysctl_w("net.ipv4.ip_local_port_range", "32768 61000") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900308 LOG(ERROR) << "Failed to restore local port range";
309 }
Garrick Evans7cf8c542020-05-25 09:50:17 +0900310 // Disable packet forwarding
311 if (runner.sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0) {
312 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
313 }
314 if (runner.sysctl_w("net.ipv4.ip_forward", "0") != 0) {
315 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
316 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800317}
318
Garrick Evans4c042572019-12-17 13:42:25 +0900319void Manager::OnSubprocessExited(pid_t pid, const siginfo_t&) {
320 LOG(ERROR) << "Subprocess " << pid << " exited unexpectedly -"
321 << " attempting to restart";
322
323 HelperProcess* proc;
324 if (pid == adb_proxy_->pid()) {
325 proc = adb_proxy_.get();
326 } else if (pid == mcast_proxy_->pid()) {
327 proc = mcast_proxy_.get();
328 } else if (pid == nd_proxy_->pid()) {
329 proc = nd_proxy_.get();
330 } else {
331 LOG(DFATAL) << "Unknown child process";
332 return;
333 }
334
335 process_reaper_.ForgetChild(pid);
336
hschamf9546312020-04-14 15:12:40 +0900337 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Garrick Evans4c042572019-12-17 13:42:25 +0900338 FROM_HERE,
339 base::Bind(&Manager::RestartSubprocess, weak_factory_.GetWeakPtr(), proc),
340 base::TimeDelta::FromMilliseconds((2 << proc->restarts()) *
341 kSubprocessRestartDelayMs));
342}
343
344void Manager::RestartSubprocess(HelperProcess* subproc) {
345 if (subproc->Restart()) {
346 DCHECK(process_reaper_.WatchForChild(
347 FROM_HERE, subproc->pid(),
348 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
349 subproc->pid())))
350 << "Failed to watch child process " << subproc->pid();
351 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800352}
353
Garrick Evanse94a14e2019-11-11 10:32:13 +0900354bool Manager::StartArc(pid_t pid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900355 if (!arc_svc_->Start(pid))
356 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900357
358 GuestMessage msg;
359 msg.set_event(GuestMessage::START);
360 msg.set_type(GuestMessage::ARC);
361 msg.set_arc_pid(pid);
362 SendGuestMessage(msg);
363
364 return true;
365}
366
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900367void Manager::StopArc() {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900368 GuestMessage msg;
369 msg.set_event(GuestMessage::STOP);
370 msg.set_type(GuestMessage::ARC);
371 SendGuestMessage(msg);
372
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900373 // After the ARC container has stopped, the pid is not known anymore.
374 // The pid argument is ignored by ArcService.
375 arc_svc_->Stop(0);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900376}
377
Garrick Evans015b0d62020-02-07 09:06:38 +0900378bool Manager::StartArcVm(uint32_t cid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900379 if (!arc_svc_->Start(cid))
380 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900381
382 GuestMessage msg;
383 msg.set_event(GuestMessage::START);
384 msg.set_type(GuestMessage::ARC_VM);
385 msg.set_arcvm_vsock_cid(cid);
386 SendGuestMessage(msg);
387
388 return true;
389}
390
Garrick Evans015b0d62020-02-07 09:06:38 +0900391void Manager::StopArcVm(uint32_t cid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900392 GuestMessage msg;
393 msg.set_event(GuestMessage::STOP);
394 msg.set_type(GuestMessage::ARC_VM);
395 SendGuestMessage(msg);
396
Garrick Evans21173b12019-11-20 15:23:16 +0900397 arc_svc_->Stop(cid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900398}
399
Garrick Evans51d5b552020-01-30 10:42:06 +0900400bool Manager::StartCrosVm(uint64_t vm_id,
401 GuestMessage::GuestType vm_type,
Garrick Evans53a2a982020-02-05 10:53:35 +0900402 uint32_t subnet_index) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900403 DCHECK(vm_type == GuestMessage::TERMINA_VM ||
404 vm_type == GuestMessage::PLUGIN_VM);
405
406 if (!cros_svc_->Start(vm_id, vm_type == GuestMessage::TERMINA_VM,
407 subnet_index))
Garrick Evans47c19272019-11-21 10:58:21 +0900408 return false;
409
410 GuestMessage msg;
411 msg.set_event(GuestMessage::START);
Garrick Evans51d5b552020-01-30 10:42:06 +0900412 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900413 SendGuestMessage(msg);
414
415 return true;
416}
417
Garrick Evans51d5b552020-01-30 10:42:06 +0900418void Manager::StopCrosVm(uint64_t vm_id, GuestMessage::GuestType vm_type) {
Garrick Evans47c19272019-11-21 10:58:21 +0900419 GuestMessage msg;
420 msg.set_event(GuestMessage::STOP);
Garrick Evans51d5b552020-01-30 10:42:06 +0900421 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900422 SendGuestMessage(msg);
423
Garrick Evans51d5b552020-01-30 10:42:06 +0900424 cros_svc_->Stop(vm_id, vm_type == GuestMessage::TERMINA_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900425}
426
Garrick Evans08843932019-09-17 14:41:08 +0900427std::unique_ptr<dbus::Response> Manager::OnArcStartup(
428 dbus::MethodCall* method_call) {
429 LOG(INFO) << "ARC++ starting up";
430
431 std::unique_ptr<dbus::Response> dbus_response(
432 dbus::Response::FromMethodCall(method_call));
433
434 dbus::MessageReader reader(method_call);
435 dbus::MessageWriter writer(dbus_response.get());
436
437 patchpanel::ArcStartupRequest request;
438 patchpanel::ArcStartupResponse response;
439
440 if (!reader.PopArrayOfBytesAsProto(&request)) {
441 LOG(ERROR) << "Unable to parse request";
442 writer.AppendProtoAsArrayOfBytes(response);
443 return dbus_response;
444 }
445
Garrick Evanse01bf072019-11-15 09:08:19 +0900446 if (!StartArc(request.pid()))
447 LOG(ERROR) << "Failed to start ARC++ network service";
Garrick Evanse94a14e2019-11-11 10:32:13 +0900448
Garrick Evans08843932019-09-17 14:41:08 +0900449 writer.AppendProtoAsArrayOfBytes(response);
450 return dbus_response;
451}
452
453std::unique_ptr<dbus::Response> Manager::OnArcShutdown(
454 dbus::MethodCall* method_call) {
455 LOG(INFO) << "ARC++ shutting down";
456
457 std::unique_ptr<dbus::Response> dbus_response(
458 dbus::Response::FromMethodCall(method_call));
459
460 dbus::MessageReader reader(method_call);
461 dbus::MessageWriter writer(dbus_response.get());
462
463 patchpanel::ArcShutdownRequest request;
464 patchpanel::ArcShutdownResponse response;
465
466 if (!reader.PopArrayOfBytesAsProto(&request)) {
467 LOG(ERROR) << "Unable to parse request";
468 writer.AppendProtoAsArrayOfBytes(response);
469 return dbus_response;
470 }
471
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900472 StopArc();
Garrick Evanse94a14e2019-11-11 10:32:13 +0900473
Garrick Evans08843932019-09-17 14:41:08 +0900474 writer.AppendProtoAsArrayOfBytes(response);
475 return dbus_response;
476}
477
478std::unique_ptr<dbus::Response> Manager::OnArcVmStartup(
479 dbus::MethodCall* method_call) {
480 LOG(INFO) << "ARCVM starting up";
481
482 std::unique_ptr<dbus::Response> dbus_response(
483 dbus::Response::FromMethodCall(method_call));
484
485 dbus::MessageReader reader(method_call);
486 dbus::MessageWriter writer(dbus_response.get());
487
488 patchpanel::ArcVmStartupRequest request;
489 patchpanel::ArcVmStartupResponse response;
490
491 if (!reader.PopArrayOfBytesAsProto(&request)) {
492 LOG(ERROR) << "Unable to parse request";
493 writer.AppendProtoAsArrayOfBytes(response);
494 return dbus_response;
495 }
496
Garrick Evans47c19272019-11-21 10:58:21 +0900497 if (!StartArcVm(request.cid())) {
Garrick Evanse01bf072019-11-15 09:08:19 +0900498 LOG(ERROR) << "Failed to start ARCVM network service";
Garrick Evans47c19272019-11-21 10:58:21 +0900499 writer.AppendProtoAsArrayOfBytes(response);
500 return dbus_response;
Garrick Evanse01bf072019-11-15 09:08:19 +0900501 }
Garrick Evanse94a14e2019-11-11 10:32:13 +0900502
Garrick Evans47c19272019-11-21 10:58:21 +0900503 // Populate the response with the known devices.
Garrick Evans38b25a42020-04-06 15:17:42 +0900504 for (const auto* config : arc_svc_->GetDeviceConfigs()) {
505 if (config->tap_ifname().empty())
506 continue;
Garrick Evans47c19272019-11-21 10:58:21 +0900507
Garrick Evans38b25a42020-04-06 15:17:42 +0900508 auto* dev = response.add_devices();
509 dev->set_ifname(config->tap_ifname());
510 dev->set_ipv4_addr(config->guest_ipv4_addr());
511 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900512
Garrick Evans08843932019-09-17 14:41:08 +0900513 writer.AppendProtoAsArrayOfBytes(response);
514 return dbus_response;
515}
516
517std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
518 dbus::MethodCall* method_call) {
519 LOG(INFO) << "ARCVM shutting down";
520
521 std::unique_ptr<dbus::Response> dbus_response(
522 dbus::Response::FromMethodCall(method_call));
523
524 dbus::MessageReader reader(method_call);
525 dbus::MessageWriter writer(dbus_response.get());
526
527 patchpanel::ArcVmShutdownRequest request;
528 patchpanel::ArcVmShutdownResponse response;
529
530 if (!reader.PopArrayOfBytesAsProto(&request)) {
531 LOG(ERROR) << "Unable to parse request";
532 writer.AppendProtoAsArrayOfBytes(response);
533 return dbus_response;
534 }
535
Garrick Evans21173b12019-11-20 15:23:16 +0900536 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900537
Garrick Evans08843932019-09-17 14:41:08 +0900538 writer.AppendProtoAsArrayOfBytes(response);
539 return dbus_response;
540}
541
Garrick Evans47c19272019-11-21 10:58:21 +0900542std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
543 dbus::MethodCall* method_call) {
544 LOG(INFO) << "Termina VM starting up";
545
546 std::unique_ptr<dbus::Response> dbus_response(
547 dbus::Response::FromMethodCall(method_call));
548
549 dbus::MessageReader reader(method_call);
550 dbus::MessageWriter writer(dbus_response.get());
551
552 patchpanel::TerminaVmStartupRequest request;
553 patchpanel::TerminaVmStartupResponse response;
554
555 if (!reader.PopArrayOfBytesAsProto(&request)) {
556 LOG(ERROR) << "Unable to parse request";
557 writer.AppendProtoAsArrayOfBytes(response);
558 return dbus_response;
559 }
560
561 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900562 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900563 LOG(ERROR) << "Failed to start Termina VM network service";
564 writer.AppendProtoAsArrayOfBytes(response);
565 return dbus_response;
566 }
567
Garrick Evans51d5b552020-01-30 10:42:06 +0900568 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900569 if (!tap) {
570 LOG(DFATAL) << "TAP device missing";
571 writer.AppendProtoAsArrayOfBytes(response);
572 return dbus_response;
573 }
Garrick Evans47c19272019-11-21 10:58:21 +0900574
Garrick Evansb1c93712020-01-22 09:28:25 +0900575 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900576 dev->set_ifname(tap->host_ifname());
577 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900578 if (!subnet) {
579 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
580 writer.AppendProtoAsArrayOfBytes(response);
581 return dbus_response;
582 }
583 auto* resp_subnet = dev->mutable_ipv4_subnet();
584 resp_subnet->set_base_addr(subnet->BaseAddress());
585 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900586 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900587 if (!subnet) {
588 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
589 writer.AppendProtoAsArrayOfBytes(response);
590 return dbus_response;
591 }
592 resp_subnet = response.mutable_container_subnet();
593 resp_subnet->set_base_addr(subnet->BaseAddress());
594 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900595
596 writer.AppendProtoAsArrayOfBytes(response);
597 return dbus_response;
598}
599
600std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
601 dbus::MethodCall* method_call) {
602 LOG(INFO) << "Termina VM shutting down";
603
604 std::unique_ptr<dbus::Response> dbus_response(
605 dbus::Response::FromMethodCall(method_call));
606
607 dbus::MessageReader reader(method_call);
608 dbus::MessageWriter writer(dbus_response.get());
609
610 patchpanel::TerminaVmShutdownRequest request;
611 patchpanel::TerminaVmShutdownResponse response;
612
613 if (!reader.PopArrayOfBytesAsProto(&request)) {
614 LOG(ERROR) << "Unable to parse request";
615 writer.AppendProtoAsArrayOfBytes(response);
616 return dbus_response;
617 }
618
Garrick Evans51d5b552020-01-30 10:42:06 +0900619 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
620
621 writer.AppendProtoAsArrayOfBytes(response);
622 return dbus_response;
623}
624
625std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
626 dbus::MethodCall* method_call) {
627 LOG(INFO) << "Plugin VM starting up";
628
629 std::unique_ptr<dbus::Response> dbus_response(
630 dbus::Response::FromMethodCall(method_call));
631
632 dbus::MessageReader reader(method_call);
633 dbus::MessageWriter writer(dbus_response.get());
634
635 patchpanel::PluginVmStartupRequest request;
636 patchpanel::PluginVmStartupResponse response;
637
638 if (!reader.PopArrayOfBytesAsProto(&request)) {
639 LOG(ERROR) << "Unable to parse request";
640 writer.AppendProtoAsArrayOfBytes(response);
641 return dbus_response;
642 }
643
Garrick Evans08fb34b2020-02-20 10:50:17 +0900644 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900645 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900646 LOG(ERROR) << "Failed to start Plugin VM network service";
647 writer.AppendProtoAsArrayOfBytes(response);
648 return dbus_response;
649 }
650
651 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
652 if (!tap) {
653 LOG(DFATAL) << "TAP device missing";
654 writer.AppendProtoAsArrayOfBytes(response);
655 return dbus_response;
656 }
657
Garrick Evans51d5b552020-01-30 10:42:06 +0900658 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900659 dev->set_ifname(tap->host_ifname());
660 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900661 if (!subnet) {
662 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
663 writer.AppendProtoAsArrayOfBytes(response);
664 return dbus_response;
665 }
666 auto* resp_subnet = dev->mutable_ipv4_subnet();
667 resp_subnet->set_base_addr(subnet->BaseAddress());
668 resp_subnet->set_prefix_len(subnet->PrefixLength());
669
670 writer.AppendProtoAsArrayOfBytes(response);
671 return dbus_response;
672}
673
674std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
675 dbus::MethodCall* method_call) {
676 LOG(INFO) << "Plugin VM shutting down";
677
678 std::unique_ptr<dbus::Response> dbus_response(
679 dbus::Response::FromMethodCall(method_call));
680
681 dbus::MessageReader reader(method_call);
682 dbus::MessageWriter writer(dbus_response.get());
683
684 patchpanel::PluginVmShutdownRequest request;
685 patchpanel::PluginVmShutdownResponse response;
686
687 if (!reader.PopArrayOfBytesAsProto(&request)) {
688 LOG(ERROR) << "Unable to parse request";
689 writer.AppendProtoAsArrayOfBytes(response);
690 return dbus_response;
691 }
692
693 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900694
695 writer.AppendProtoAsArrayOfBytes(response);
696 return dbus_response;
697}
698
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900699std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
700 dbus::MethodCall* method_call) {
701 std::unique_ptr<dbus::Response> dbus_response(
702 dbus::Response::FromMethodCall(method_call));
703
704 dbus::MessageReader reader(method_call);
705 dbus::MessageWriter writer(dbus_response.get());
706
707 patchpanel::SetVpnIntentRequest request;
708 patchpanel::SetVpnIntentResponse response;
709
710 bool success = reader.PopArrayOfBytesAsProto(&request);
711 if (!success) {
712 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
713 // Do not return yet to make sure we close the received fd.
714 }
715
716 base::ScopedFD client_socket;
717 reader.PopFileDescriptor(&client_socket);
718
719 if (success)
720 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
721
722 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900723
724 writer.AppendProtoAsArrayOfBytes(response);
725 return dbus_response;
726}
727
728std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
729 dbus::MethodCall* method_call) {
730 std::unique_ptr<dbus::Response> dbus_response(
731 dbus::Response::FromMethodCall(method_call));
732
733 dbus::MessageReader reader(method_call);
734 dbus::MessageWriter writer(dbus_response.get());
735
736 patchpanel::ConnectNamespaceRequest request;
737 patchpanel::ConnectNamespaceResponse response;
738
Hugo Benichicc6850f2020-01-17 13:26:06 +0900739 bool success = true;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900740 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900741 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
742 // Do not return yet to make sure we close the received fd and
743 // validate other arguments.
744 success = false;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900745 }
746
Hugo Benichicc6850f2020-01-17 13:26:06 +0900747 base::ScopedFD client_fd;
748 reader.PopFileDescriptor(&client_fd);
749 if (!client_fd.is_valid()) {
750 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
751 success = false;
752 }
753
754 pid_t pid = request.pid();
755 {
756 ScopedNS ns(pid);
757 if (!ns.IsValid()) {
758 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
759 success = false;
760 }
761 }
762
763 const std::string& outbound_ifname = request.outbound_physical_device();
764 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
765 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
766 << outbound_ifname;
767 success = false;
768 }
769
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900770 if (success)
771 ConnectNamespace(std::move(client_fd), request, response);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900772
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900773 writer.AppendProtoAsArrayOfBytes(response);
774 return dbus_response;
775}
776
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900777void Manager::ConnectNamespace(
778 base::ScopedFD client_fd,
779 const patchpanel::ConnectNamespaceRequest& request,
780 patchpanel::ConnectNamespaceResponse& response) {
781 std::unique_ptr<Subnet> subnet =
782 addr_mgr_.AllocateIPv4Subnet(AddressManager::Guest::MINIJAIL_NETNS);
783 if (!subnet) {
784 LOG(ERROR) << "ConnectNamespaceRequest: exhausted IPv4 subnet space";
785 return;
786 }
787
788 const std::string ifname_id = std::to_string(connected_namespaces_next_id_);
Hugo Benichi33860d72020-07-09 16:34:01 +0900789 const std::string netns_name = "connected_netns_" + ifname_id;
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900790 const std::string host_ifname = "arc_ns" + ifname_id;
791 const std::string client_ifname = "veth" + ifname_id;
Hugo Benichie8758b52020-04-03 14:49:01 +0900792 const uint32_t host_ipv4_addr = subnet->AddressAtOffset(0);
793 const uint32_t client_ipv4_addr = subnet->AddressAtOffset(1);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900794
Hugo Benichie8758b52020-04-03 14:49:01 +0900795 // Veth interface configuration and client routing configuration:
Hugo Benichi33860d72020-07-09 16:34:01 +0900796 // - attach a name to the client namespace.
797 // - create veth pair across the current namespace and the client namespace.
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900798 // - configure IPv4 address on remote veth inside client namespace.
Hugo Benichie8758b52020-04-03 14:49:01 +0900799 // - configure IPv4 address on local veth inside host namespace.
800 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichie8758b52020-04-03 14:49:01 +0900801 pid_t pid = request.pid();
Hugo Benichi33860d72020-07-09 16:34:01 +0900802 if (!datapath_->NetnsAttachName(netns_name, pid)) {
803 LOG(ERROR) << "ConnectNamespaceRequest: failed to attach name "
804 << netns_name << " to namespace pid " << pid;
805 return;
806 }
807 if (!datapath_->ConnectVethPair(pid, netns_name, host_ifname, client_ifname,
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900808 addr_mgr_.GenerateMacAddress(),
809 client_ipv4_addr, subnet->PrefixLength(),
810 false /* enable_multicast */)) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900811 LOG(ERROR) << "ConnectNamespaceRequest: failed to create veth pair for "
812 "namespace pid "
813 << pid;
Hugo Benichi33860d72020-07-09 16:34:01 +0900814 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900815 return;
816 }
817 if (!datapath_->ConfigureInterface(
818 host_ifname, addr_mgr_.GenerateMacAddress(), host_ipv4_addr,
819 subnet->PrefixLength(), true /* link up */,
820 false /* enable_multicast */)) {
821 LOG(ERROR) << "ConnectNamespaceRequest: cannot configure host interface "
822 << host_ifname;
823 datapath_->RemoveInterface(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900824 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900825 return;
826 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900827 bool peer_route_setup_success;
Hugo Benichie8758b52020-04-03 14:49:01 +0900828 {
829 ScopedNS ns(pid);
Hugo Benichi33860d72020-07-09 16:34:01 +0900830 peer_route_setup_success =
831 ns.IsValid() &&
832 datapath_->AddIPv4Route(host_ipv4_addr, INADDR_ANY, INADDR_ANY);
833 }
834 if (!peer_route_setup_success) {
835 LOG(ERROR) << "ConnectNamespaceRequest: failed to add default /0 route to "
836 << host_ifname << " inside namespace pid " << pid;
837 datapath_->RemoveInterface(host_ifname);
838 datapath_->NetnsDeleteName(netns_name);
839 return;
Hugo Benichie8758b52020-04-03 14:49:01 +0900840 }
841
842 // Host namespace routing configuration
843 // - ingress: add route to client subnet via |host_ifname|.
844 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
845 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
846 // Note that by default unsolicited ingress traffic is not forwarded to the
847 // client namespace unless the client specifically set port forwarding
848 // through permission_broker DBus APIs.
849 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
850 // both ways between client namespace and other guest containers and VMs.
851 // TODO(hugobenichi) If outbound_physical_device is defined, then set strong
852 // routing to that interface routing table.
853 if (!datapath_->AddIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
854 subnet->Netmask())) {
855 LOG(ERROR)
856 << "ConnectNamespaceRequest: failed to set route to client namespace";
857 datapath_->RemoveInterface(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900858 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900859 return;
860 }
861 if (!datapath_->AddOutboundIPv4(host_ifname)) {
862 LOG(ERROR) << "ConnectNamespaceRequest: failed to allow FORWARD for "
863 "traffic outgoing from "
864 << host_ifname;
865 datapath_->RemoveInterface(host_ifname);
866 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
867 subnet->Netmask());
Hugo Benichi33860d72020-07-09 16:34:01 +0900868 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900869 return;
870 }
871 if (!datapath_->AddOutboundIPv4SNATMark(host_ifname)) {
872 LOG(ERROR) << "ConnectNamespaceRequest: failed to set SNAT for traffic "
873 "outgoing from "
874 << host_ifname;
875 datapath_->RemoveInterface(host_ifname);
876 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
877 subnet->Netmask());
878 datapath_->RemoveOutboundIPv4(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900879 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900880 return;
881 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900882
Hugo Benichi7352ad92020-04-07 16:11:59 +0900883 // Dup the client fd into our own: this guarantees that the fd number will
884 // be stable and tied to the actual kernel resources used by the client.
885 base::ScopedFD local_client_fd(dup(client_fd.get()));
886 if (!local_client_fd.is_valid()) {
887 PLOG(ERROR) << "ConnectNamespaceRequest: failed to dup() client fd";
Hugo Benichie8758b52020-04-03 14:49:01 +0900888 datapath_->RemoveInterface(host_ifname);
889 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
890 subnet->Netmask());
891 datapath_->RemoveOutboundIPv4(host_ifname);
892 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900893 datapath_->NetnsDeleteName(netns_name);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900894 return;
895 }
896
897 // Add the dupe fd to the epoll watcher.
898 // TODO(hugobenichi) Find a way to reuse base::FileDescriptorWatcher for
899 // listening to EPOLLHUP.
900 struct epoll_event epevent;
901 epevent.events = EPOLLIN; // EPOLLERR | EPOLLHUP are always waited for.
902 epevent.data.fd = local_client_fd.get();
903 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_ADD,
904 local_client_fd.get(), &epevent) != 0) {
905 PLOG(ERROR) << "ConnectNamespaceResponse: epoll_ctl(EPOLL_CTL_ADD) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900906 datapath_->RemoveInterface(host_ifname);
907 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
908 subnet->Netmask());
909 datapath_->RemoveOutboundIPv4(host_ifname);
910 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900911 datapath_->NetnsDeleteName(netns_name);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900912 return;
913 }
914
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900915 // Prepare the response before storing ConnectNamespaceInfo.
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900916 response.set_peer_ifname(client_ifname);
917 response.set_peer_ipv4_address(host_ipv4_addr);
918 response.set_host_ifname(host_ifname);
919 response.set_host_ipv4_address(client_ipv4_addr);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900920 auto* response_subnet = response.mutable_ipv4_subnet();
921 response_subnet->set_base_addr(subnet->BaseAddress());
922 response_subnet->set_prefix_len(subnet->PrefixLength());
923
924 // Store ConnectNamespaceInfo
925 connected_namespaces_next_id_++;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900926 int fdkey = local_client_fd.release();
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900927 connected_namespaces_[fdkey] = {};
928 ConnectNamespaceInfo& ns_info = connected_namespaces_[fdkey];
929 ns_info.pid = request.pid();
Hugo Benichi33860d72020-07-09 16:34:01 +0900930 ns_info.netns_name = std::move(netns_name);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900931 ns_info.outbound_ifname = request.outbound_physical_device();
932 ns_info.host_ifname = std::move(host_ifname);
933 ns_info.client_ifname = std::move(client_ifname);
934 ns_info.client_subnet = std::move(subnet);
935
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900936 LOG(INFO) << "Connected network namespace " << ns_info;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900937
938 if (connected_namespaces_.size() == 1) {
939 LOG(INFO) << "Starting ConnectNamespace client fds monitoring";
940 CheckConnectedNamespaces();
941 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900942}
943
944void Manager::DisconnectNamespace(int client_fd) {
945 auto it = connected_namespaces_.find(client_fd);
946 if (it == connected_namespaces_.end()) {
947 LOG(ERROR) << "No ConnectNamespaceInfo found for client_fd " << client_fd;
948 return;
949 }
950
Hugo Benichi7352ad92020-04-07 16:11:59 +0900951 // Remove the client fd dupe from the epoll watcher and close it.
952 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL, client_fd,
Hugo Benichie8758b52020-04-03 14:49:01 +0900953 nullptr) != 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900954 PLOG(ERROR) << "DisconnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900955 if (close(client_fd) < 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900956 PLOG(ERROR) << "DisconnectNamespace: close(client_fd) failed";
Hugo Benichi7352ad92020-04-07 16:11:59 +0900957
Hugo Benichie8758b52020-04-03 14:49:01 +0900958 // Destroy the interface configuration and routing configuration:
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900959 // - destroy veth pair.
Hugo Benichie8758b52020-04-03 14:49:01 +0900960 // - remove forwarding rules on host namespace.
961 // - remove SNAT marking rule on host namespace.
Hugo Benichi33860d72020-07-09 16:34:01 +0900962 // Delete the network namespace attached to the client namespace.
Hugo Benichie8758b52020-04-03 14:49:01 +0900963 // Note that the default route set inside the client namespace by patchpanel
964 // is not destroyed: it is assumed the client will also teardown its
965 // namespace if it triggered DisconnectNamespace.
966 datapath_->RemoveInterface(it->second.host_ifname);
967 datapath_->RemoveOutboundIPv4(it->second.host_ifname);
968 datapath_->RemoveOutboundIPv4SNATMark(it->second.host_ifname);
969 datapath_->DeleteIPv4Route(it->second.client_subnet->AddressAtOffset(0),
970 it->second.client_subnet->BaseAddress(),
971 it->second.client_subnet->Netmask());
Hugo Benichi33860d72020-07-09 16:34:01 +0900972 datapath_->NetnsDeleteName(it->second.netns_name);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900973
974 LOG(INFO) << "Disconnected network namespace " << it->second;
975
976 // This release the allocated IPv4 subnet.
977 connected_namespaces_.erase(it);
978}
979
Hugo Benichi7352ad92020-04-07 16:11:59 +0900980// TODO(hugobenichi) Generalize this check to all resources created by
981// patchpanel on behalf of a remote client.
982void Manager::CheckConnectedNamespaces() {
983 int max_event = 10;
984 struct epoll_event epevents[max_event];
985 int nready = epoll_wait(connected_namespaces_epollfd_, epevents, max_event,
986 0 /* do not block */);
987 if (nready < 0)
988 PLOG(ERROR) << "CheckConnectedNamespaces: epoll_wait(0) failed";
989
990 for (int i = 0; i < nready; i++)
991 if (epevents[i].events & (EPOLLHUP | EPOLLERR))
992 DisconnectNamespace(epevents[i].data.fd);
993
994 if (connected_namespaces_.empty()) {
995 LOG(INFO) << "Stopping ConnectNamespace client fds monitoring";
996 return;
997 }
998
Qijiang Fan2d7aeb42020-05-19 02:06:39 +0900999 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Hugo Benichi7352ad92020-04-07 16:11:59 +09001000 FROM_HERE,
1001 base::Bind(&Manager::CheckConnectedNamespaces,
Hugo Benichie8758b52020-04-03 14:49:01 +09001002 weak_factory_.GetWeakPtr()),
Hugo Benichi7352ad92020-04-07 16:11:59 +09001003 kConnectNamespaceCheckInterval);
1004}
1005
Garrick Evanse94a14e2019-11-11 10:32:13 +09001006void Manager::SendGuestMessage(const GuestMessage& msg) {
Garrick Evans96e03042019-05-28 14:30:52 +09001007 IpHelperMessage ipm;
1008 *ipm.mutable_guest_message() = msg;
Garrick Evans96e03042019-05-28 14:30:52 +09001009 adb_proxy_->SendMessage(ipm);
Garrick Evanse94a14e2019-11-11 10:32:13 +09001010 mcast_proxy_->SendMessage(ipm);
1011 nd_proxy_->SendMessage(ipm);
Garrick Evans96e03042019-05-28 14:30:52 +09001012}
1013
Garrick Evans4ac09852020-01-16 14:09:22 +09001014void Manager::StartForwarding(const std::string& ifname_physical,
1015 const std::string& ifname_virtual,
Garrick Evans4ac09852020-01-16 14:09:22 +09001016 bool ipv6,
1017 bool multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001018 if (ifname_physical.empty() || ifname_virtual.empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001019 return;
1020
1021 IpHelperMessage ipm;
1022 DeviceMessage* msg = ipm.mutable_device_message();
1023 msg->set_dev_ifname(ifname_physical);
Garrick Evans4ac09852020-01-16 14:09:22 +09001024 msg->set_br_ifname(ifname_virtual);
1025
1026 if (ipv6) {
1027 LOG(INFO) << "Starting IPv6 forwarding from " << ifname_physical << " to "
1028 << ifname_virtual;
1029
1030 if (!datapath_->AddIPv6Forwarding(ifname_physical, ifname_virtual)) {
1031 LOG(ERROR) << "Failed to setup iptables forwarding rule for IPv6 from "
1032 << ifname_physical << " to " << ifname_virtual;
1033 }
1034 if (!datapath_->MaskInterfaceFlags(ifname_physical, IFF_ALLMULTI)) {
1035 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1036 << ifname_physical;
1037 }
1038 if (!datapath_->MaskInterfaceFlags(ifname_virtual, IFF_ALLMULTI)) {
1039 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1040 << ifname_virtual;
1041 }
1042 nd_proxy_->SendMessage(ipm);
1043 }
1044
1045 if (multicast) {
1046 LOG(INFO) << "Starting multicast forwarding from " << ifname_physical
1047 << " to " << ifname_virtual;
1048 mcast_proxy_->SendMessage(ipm);
1049 }
1050}
1051
1052void Manager::StopForwarding(const std::string& ifname_physical,
1053 const std::string& ifname_virtual,
1054 bool ipv6,
1055 bool multicast) {
1056 if (ifname_physical.empty())
1057 return;
1058
1059 IpHelperMessage ipm;
1060 DeviceMessage* msg = ipm.mutable_device_message();
1061 msg->set_dev_ifname(ifname_physical);
1062 msg->set_teardown(true);
Taoyu Li7dca19a2020-03-16 16:27:07 +09001063 if (!ifname_virtual.empty()) {
1064 msg->set_br_ifname(ifname_virtual);
1065 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001066
1067 if (ipv6) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001068 if (ifname_virtual.empty()) {
1069 LOG(INFO) << "Stopping IPv6 forwarding on " << ifname_physical;
1070 } else {
1071 LOG(INFO) << "Stopping IPv6 forwarding from " << ifname_physical << " to "
1072 << ifname_virtual;
1073 datapath_->RemoveIPv6Forwarding(ifname_physical, ifname_virtual);
1074 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001075 nd_proxy_->SendMessage(ipm);
1076 }
1077
1078 if (multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001079 if (ifname_virtual.empty()) {
1080 LOG(INFO) << "Stopping multicast forwarding on " << ifname_physical;
1081 } else {
1082 LOG(INFO) << "Stopping multicast forwarding from " << ifname_physical
1083 << " to " << ifname_virtual;
1084 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001085 mcast_proxy_->SendMessage(ipm);
1086 }
1087}
1088
Garrick Evans4ac09852020-01-16 14:09:22 +09001089void Manager::OnDeviceMessageFromNDProxy(const DeviceMessage& msg) {
1090 LOG_IF(DFATAL, msg.dev_ifname().empty())
1091 << "Received DeviceMessage w/ empty dev_ifname";
1092
1093 if (!datapath_->AddIPv6HostRoute(msg.dev_ifname(), msg.guest_ip6addr(),
1094 128)) {
1095 LOG(WARNING) << "Failed to setup the IPv6 route for interface "
1096 << msg.dev_ifname();
1097 }
1098}
1099
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001100std::ostream& operator<<(std::ostream& stream,
1101 const Manager::ConnectNamespaceInfo& ns_info) {
1102 stream << "{ pid: " << ns_info.pid;
1103 if (!ns_info.outbound_ifname.empty()) {
1104 stream << ", outbound_ifname: " << ns_info.outbound_ifname;
1105 }
1106 stream << ", host_ifname: " << ns_info.host_ifname
1107 << ", client_ifname: " << ns_info.client_ifname
1108 << ", subnet: " << ns_info.client_subnet->ToCidrString() << '}';
1109 return stream;
1110}
1111
Garrick Evans3388a032020-03-24 11:25:55 +09001112} // namespace patchpanel