blob: 3218586425248c8a45510323baa984b4b1e29643 [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},
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900199 {patchpanel::kModifyPortRuleMethod, &Manager::OnModifyPortRule},
Garrick Evans08843932019-09-17 14:41:08 +0900200 };
201
202 for (const auto& kv : kServiceMethods) {
203 if (!dbus_svc_path_->ExportMethodAndBlock(
204 patchpanel::kPatchPanelInterface, kv.first,
205 base::Bind(&HandleSynchronousDBusMethodCall,
206 base::Bind(kv.second, base::Unretained(this))))) {
207 LOG(FATAL) << "Failed to export method " << kv.first;
208 }
209 }
210
211 if (!bus_->RequestOwnershipAndBlock(patchpanel::kPatchPanelServiceName,
212 dbus::Bus::REQUIRE_PRIMARY)) {
213 LOG(FATAL) << "Failed to take ownership of "
214 << patchpanel::kPatchPanelServiceName;
215 }
216 LOG(INFO) << "DBus service interface ready";
217
Taoyu Li6d479442019-12-09 13:02:29 +0900218 auto& runner = datapath_->runner();
Garrick Evans7cf8c542020-05-25 09:50:17 +0900219 // Enable IPv4 packet forwarding
220 if (runner.sysctl_w("net.ipv4.ip_forward", "1") != 0) {
221 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
222 << " Guest connectivity will not work correctly.";
223 }
Garrick Evans28d194e2019-12-17 10:22:28 +0900224 // Limit local port range: Android owns 47104-61000.
225 // TODO(garrick): The original history behind this tweak is gone. Some
226 // investigation is needed to see if it is still applicable.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900227 if (runner.sysctl_w("net.ipv4.ip_local_port_range", "32768 47103") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900228 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
229 << " apps may not work correctly.";
230 }
Taoyu Li6d479442019-12-09 13:02:29 +0900231 // Enable IPv6 packet forarding
Garrick Evans8e8e3472020-01-23 14:03:50 +0900232 if (runner.sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0) {
Taoyu Li6d479442019-12-09 13:02:29 +0900233 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
234 << " IPv6 functionality may be broken.";
235 }
236 // Kernel proxy_ndp is only needed for legacy IPv6 configuration
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +0900237 if (!ShouldEnableFeature(kNDProxyMinAndroidSdkVersion,
Garrick Evansf5862122020-03-16 09:13:45 +0900238 kNDProxyMinChromeMilestone, {},
239 kNDProxyFeatureName) &&
Garrick Evans8e8e3472020-01-23 14:03:50 +0900240 runner.sysctl_w("net.ipv6.conf.all.proxy_ndp", "1") != 0) {
Taoyu Li6d479442019-12-09 13:02:29 +0900241 LOG(ERROR) << "Failed to update net.ipv6.conf.all.proxy_ndp."
242 << " IPv6 functionality may be broken.";
243 }
244
Garrick Evansd291af62020-05-25 10:39:06 +0900245 if (!datapath_->AddSNATMarkRules()) {
246 LOG(ERROR) << "Failed to install SNAT mark rules."
247 << " Guest connectivity may be broken.";
248 }
249 if (!datapath_->AddForwardEstablishedRule()) {
250 LOG(ERROR) << "Failed to install forwarding rule for established"
251 << " connections.";
252 }
253
Garrick Evansff6e37f2020-05-25 10:54:47 +0900254 // TODO(chromium:898210): Move interface-specific masquerading setup to shill;
255 // such that we can better set up the masquerade rules based on connection
256 // type rather than interface names.
257 if (!datapath_->AddInterfaceSNAT("wwan+")) {
258 LOG(ERROR) << "Failed to set up wifi masquerade";
259 }
260
Garrick Evansc50426b2020-05-25 11:00:55 +0900261 if (!datapath_->AddOutboundIPv4SNATMark("vmtap+")) {
262 LOG(ERROR) << "Failed to set up NAT for TAP devices."
263 << " Guest connectivity may be broken.";
264 }
265
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900266 routing_svc_ = std::make_unique<RoutingService>();
267
Garrick Evans4ac09852020-01-16 14:09:22 +0900268 nd_proxy_->RegisterDeviceMessageHandler(base::Bind(
269 &Manager::OnDeviceMessageFromNDProxy, weak_factory_.GetWeakPtr()));
270
Garrick Evans69b85872020-02-04 11:40:26 +0900271 shill_client_ = std::make_unique<ShillClient>(bus_);
Garrick Evans1b1f67c2020-02-04 16:21:25 +0900272 auto* const forwarder = static_cast<TrafficForwarder*>(this);
Garrick Evans5d55f5e2019-07-17 15:28:10 +0900273
Hugo Benichiad1bdd92020-06-12 13:48:37 +0900274 GuestMessage::GuestType arc_guest =
275 USE_ARCVM ? GuestMessage::ARC_VM : GuestMessage::ARC;
276 arc_svc_ = std::make_unique<ArcService>(shill_client_.get(), datapath_.get(),
277 &addr_mgr_, forwarder, arc_guest);
Garrick Evans1b1f67c2020-02-04 16:21:25 +0900278 cros_svc_ = std::make_unique<CrostiniService>(shill_client_.get(), &addr_mgr_,
279 datapath_.get(), forwarder);
Jie Jiang01c1a2e2020-04-08 20:58:30 +0900280 network_monitor_svc_ =
281 std::make_unique<NetworkMonitorService>(shill_client_.get());
282 network_monitor_svc_->Start();
Taoyu Liaf944c92019-10-01 12:22:31 +0900283
284 nd_proxy_->Listen();
Long Chengd4415582019-09-24 19:16:09 +0000285}
Garrick Evans49879532018-12-03 13:15:36 +0900286
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800287void Manager::OnShutdown(int* exit_code) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900288 LOG(INFO) << "Shutting down and cleaning up";
Garrick Evans207e7482019-12-16 11:54:36 +0900289 cros_svc_.reset();
290 arc_svc_.reset();
Hugo Benichi7352ad92020-04-07 16:11:59 +0900291 close(connected_namespaces_epollfd_);
Hugo Benichie8758b52020-04-03 14:49:01 +0900292 // Tear down any remaining connected namespace.
293 std::vector<int> connected_namespaces_fdkeys;
294 for (const auto& kv : connected_namespaces_)
295 connected_namespaces_fdkeys.push_back(kv.first);
296 for (const int fdkey : connected_namespaces_fdkeys)
297 DisconnectNamespace(fdkey);
Garrick Evans28d194e2019-12-17 10:22:28 +0900298
Garrick Evansc50426b2020-05-25 11:00:55 +0900299 datapath_->RemoveOutboundIPv4SNATMark("vmtap+");
Garrick Evansff6e37f2020-05-25 10:54:47 +0900300 datapath_->RemoveInterfaceSNAT("wwan+");
Garrick Evansd291af62020-05-25 10:39:06 +0900301 datapath_->RemoveForwardEstablishedRule();
302 datapath_->RemoveSNATMarkRules();
303
Garrick Evans7cf8c542020-05-25 09:50:17 +0900304 auto& runner = datapath_->runner();
Garrick Evans28d194e2019-12-17 10:22:28 +0900305 // Restore original local port range.
306 // TODO(garrick): The original history behind this tweak is gone. Some
307 // investigation is needed to see if it is still applicable.
Garrick Evans7cf8c542020-05-25 09:50:17 +0900308 if (runner.sysctl_w("net.ipv4.ip_local_port_range", "32768 61000") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900309 LOG(ERROR) << "Failed to restore local port range";
310 }
Garrick Evans7cf8c542020-05-25 09:50:17 +0900311 // Disable packet forwarding
312 if (runner.sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0) {
313 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
314 }
315 if (runner.sysctl_w("net.ipv4.ip_forward", "0") != 0) {
316 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
317 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800318}
319
Garrick Evans4c042572019-12-17 13:42:25 +0900320void Manager::OnSubprocessExited(pid_t pid, const siginfo_t&) {
321 LOG(ERROR) << "Subprocess " << pid << " exited unexpectedly -"
322 << " attempting to restart";
323
324 HelperProcess* proc;
325 if (pid == adb_proxy_->pid()) {
326 proc = adb_proxy_.get();
327 } else if (pid == mcast_proxy_->pid()) {
328 proc = mcast_proxy_.get();
329 } else if (pid == nd_proxy_->pid()) {
330 proc = nd_proxy_.get();
331 } else {
332 LOG(DFATAL) << "Unknown child process";
333 return;
334 }
335
336 process_reaper_.ForgetChild(pid);
337
hschamf9546312020-04-14 15:12:40 +0900338 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Garrick Evans4c042572019-12-17 13:42:25 +0900339 FROM_HERE,
340 base::Bind(&Manager::RestartSubprocess, weak_factory_.GetWeakPtr(), proc),
341 base::TimeDelta::FromMilliseconds((2 << proc->restarts()) *
342 kSubprocessRestartDelayMs));
343}
344
345void Manager::RestartSubprocess(HelperProcess* subproc) {
346 if (subproc->Restart()) {
347 DCHECK(process_reaper_.WatchForChild(
348 FROM_HERE, subproc->pid(),
349 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
350 subproc->pid())))
351 << "Failed to watch child process " << subproc->pid();
352 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800353}
354
Garrick Evanse94a14e2019-11-11 10:32:13 +0900355bool Manager::StartArc(pid_t pid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900356 if (!arc_svc_->Start(pid))
357 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900358
359 GuestMessage msg;
360 msg.set_event(GuestMessage::START);
361 msg.set_type(GuestMessage::ARC);
362 msg.set_arc_pid(pid);
363 SendGuestMessage(msg);
364
365 return true;
366}
367
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900368void Manager::StopArc() {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900369 GuestMessage msg;
370 msg.set_event(GuestMessage::STOP);
371 msg.set_type(GuestMessage::ARC);
372 SendGuestMessage(msg);
373
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900374 // After the ARC container has stopped, the pid is not known anymore.
375 // The pid argument is ignored by ArcService.
376 arc_svc_->Stop(0);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900377}
378
Garrick Evans015b0d62020-02-07 09:06:38 +0900379bool Manager::StartArcVm(uint32_t cid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900380 if (!arc_svc_->Start(cid))
381 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900382
383 GuestMessage msg;
384 msg.set_event(GuestMessage::START);
385 msg.set_type(GuestMessage::ARC_VM);
386 msg.set_arcvm_vsock_cid(cid);
387 SendGuestMessage(msg);
388
389 return true;
390}
391
Garrick Evans015b0d62020-02-07 09:06:38 +0900392void Manager::StopArcVm(uint32_t cid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900393 GuestMessage msg;
394 msg.set_event(GuestMessage::STOP);
395 msg.set_type(GuestMessage::ARC_VM);
396 SendGuestMessage(msg);
397
Garrick Evans21173b12019-11-20 15:23:16 +0900398 arc_svc_->Stop(cid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900399}
400
Garrick Evans51d5b552020-01-30 10:42:06 +0900401bool Manager::StartCrosVm(uint64_t vm_id,
402 GuestMessage::GuestType vm_type,
Garrick Evans53a2a982020-02-05 10:53:35 +0900403 uint32_t subnet_index) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900404 DCHECK(vm_type == GuestMessage::TERMINA_VM ||
405 vm_type == GuestMessage::PLUGIN_VM);
406
407 if (!cros_svc_->Start(vm_id, vm_type == GuestMessage::TERMINA_VM,
408 subnet_index))
Garrick Evans47c19272019-11-21 10:58:21 +0900409 return false;
410
411 GuestMessage msg;
412 msg.set_event(GuestMessage::START);
Garrick Evans51d5b552020-01-30 10:42:06 +0900413 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900414 SendGuestMessage(msg);
415
416 return true;
417}
418
Garrick Evans51d5b552020-01-30 10:42:06 +0900419void Manager::StopCrosVm(uint64_t vm_id, GuestMessage::GuestType vm_type) {
Garrick Evans47c19272019-11-21 10:58:21 +0900420 GuestMessage msg;
421 msg.set_event(GuestMessage::STOP);
Garrick Evans51d5b552020-01-30 10:42:06 +0900422 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900423 SendGuestMessage(msg);
424
Garrick Evans51d5b552020-01-30 10:42:06 +0900425 cros_svc_->Stop(vm_id, vm_type == GuestMessage::TERMINA_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900426}
427
Garrick Evans08843932019-09-17 14:41:08 +0900428std::unique_ptr<dbus::Response> Manager::OnArcStartup(
429 dbus::MethodCall* method_call) {
430 LOG(INFO) << "ARC++ starting up";
431
432 std::unique_ptr<dbus::Response> dbus_response(
433 dbus::Response::FromMethodCall(method_call));
434
435 dbus::MessageReader reader(method_call);
436 dbus::MessageWriter writer(dbus_response.get());
437
438 patchpanel::ArcStartupRequest request;
439 patchpanel::ArcStartupResponse response;
440
441 if (!reader.PopArrayOfBytesAsProto(&request)) {
442 LOG(ERROR) << "Unable to parse request";
443 writer.AppendProtoAsArrayOfBytes(response);
444 return dbus_response;
445 }
446
Garrick Evanse01bf072019-11-15 09:08:19 +0900447 if (!StartArc(request.pid()))
448 LOG(ERROR) << "Failed to start ARC++ network service";
Garrick Evanse94a14e2019-11-11 10:32:13 +0900449
Garrick Evans08843932019-09-17 14:41:08 +0900450 writer.AppendProtoAsArrayOfBytes(response);
451 return dbus_response;
452}
453
454std::unique_ptr<dbus::Response> Manager::OnArcShutdown(
455 dbus::MethodCall* method_call) {
456 LOG(INFO) << "ARC++ shutting down";
457
458 std::unique_ptr<dbus::Response> dbus_response(
459 dbus::Response::FromMethodCall(method_call));
460
461 dbus::MessageReader reader(method_call);
462 dbus::MessageWriter writer(dbus_response.get());
463
464 patchpanel::ArcShutdownRequest request;
465 patchpanel::ArcShutdownResponse response;
466
467 if (!reader.PopArrayOfBytesAsProto(&request)) {
468 LOG(ERROR) << "Unable to parse request";
469 writer.AppendProtoAsArrayOfBytes(response);
470 return dbus_response;
471 }
472
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900473 StopArc();
Garrick Evanse94a14e2019-11-11 10:32:13 +0900474
Garrick Evans08843932019-09-17 14:41:08 +0900475 writer.AppendProtoAsArrayOfBytes(response);
476 return dbus_response;
477}
478
479std::unique_ptr<dbus::Response> Manager::OnArcVmStartup(
480 dbus::MethodCall* method_call) {
481 LOG(INFO) << "ARCVM starting up";
482
483 std::unique_ptr<dbus::Response> dbus_response(
484 dbus::Response::FromMethodCall(method_call));
485
486 dbus::MessageReader reader(method_call);
487 dbus::MessageWriter writer(dbus_response.get());
488
489 patchpanel::ArcVmStartupRequest request;
490 patchpanel::ArcVmStartupResponse response;
491
492 if (!reader.PopArrayOfBytesAsProto(&request)) {
493 LOG(ERROR) << "Unable to parse request";
494 writer.AppendProtoAsArrayOfBytes(response);
495 return dbus_response;
496 }
497
Garrick Evans47c19272019-11-21 10:58:21 +0900498 if (!StartArcVm(request.cid())) {
Garrick Evanse01bf072019-11-15 09:08:19 +0900499 LOG(ERROR) << "Failed to start ARCVM network service";
Garrick Evans47c19272019-11-21 10:58:21 +0900500 writer.AppendProtoAsArrayOfBytes(response);
501 return dbus_response;
Garrick Evanse01bf072019-11-15 09:08:19 +0900502 }
Garrick Evanse94a14e2019-11-11 10:32:13 +0900503
Garrick Evans47c19272019-11-21 10:58:21 +0900504 // Populate the response with the known devices.
Garrick Evans38b25a42020-04-06 15:17:42 +0900505 for (const auto* config : arc_svc_->GetDeviceConfigs()) {
506 if (config->tap_ifname().empty())
507 continue;
Garrick Evans47c19272019-11-21 10:58:21 +0900508
Garrick Evans38b25a42020-04-06 15:17:42 +0900509 auto* dev = response.add_devices();
510 dev->set_ifname(config->tap_ifname());
511 dev->set_ipv4_addr(config->guest_ipv4_addr());
512 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900513
Garrick Evans08843932019-09-17 14:41:08 +0900514 writer.AppendProtoAsArrayOfBytes(response);
515 return dbus_response;
516}
517
518std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
519 dbus::MethodCall* method_call) {
520 LOG(INFO) << "ARCVM shutting down";
521
522 std::unique_ptr<dbus::Response> dbus_response(
523 dbus::Response::FromMethodCall(method_call));
524
525 dbus::MessageReader reader(method_call);
526 dbus::MessageWriter writer(dbus_response.get());
527
528 patchpanel::ArcVmShutdownRequest request;
529 patchpanel::ArcVmShutdownResponse response;
530
531 if (!reader.PopArrayOfBytesAsProto(&request)) {
532 LOG(ERROR) << "Unable to parse request";
533 writer.AppendProtoAsArrayOfBytes(response);
534 return dbus_response;
535 }
536
Garrick Evans21173b12019-11-20 15:23:16 +0900537 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900538
Garrick Evans08843932019-09-17 14:41:08 +0900539 writer.AppendProtoAsArrayOfBytes(response);
540 return dbus_response;
541}
542
Garrick Evans47c19272019-11-21 10:58:21 +0900543std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
544 dbus::MethodCall* method_call) {
545 LOG(INFO) << "Termina VM starting up";
546
547 std::unique_ptr<dbus::Response> dbus_response(
548 dbus::Response::FromMethodCall(method_call));
549
550 dbus::MessageReader reader(method_call);
551 dbus::MessageWriter writer(dbus_response.get());
552
553 patchpanel::TerminaVmStartupRequest request;
554 patchpanel::TerminaVmStartupResponse response;
555
556 if (!reader.PopArrayOfBytesAsProto(&request)) {
557 LOG(ERROR) << "Unable to parse request";
558 writer.AppendProtoAsArrayOfBytes(response);
559 return dbus_response;
560 }
561
562 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900563 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900564 LOG(ERROR) << "Failed to start Termina VM network service";
565 writer.AppendProtoAsArrayOfBytes(response);
566 return dbus_response;
567 }
568
Garrick Evans51d5b552020-01-30 10:42:06 +0900569 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900570 if (!tap) {
571 LOG(DFATAL) << "TAP device missing";
572 writer.AppendProtoAsArrayOfBytes(response);
573 return dbus_response;
574 }
Garrick Evans47c19272019-11-21 10:58:21 +0900575
Garrick Evansb1c93712020-01-22 09:28:25 +0900576 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900577 dev->set_ifname(tap->host_ifname());
578 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900579 if (!subnet) {
580 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
581 writer.AppendProtoAsArrayOfBytes(response);
582 return dbus_response;
583 }
584 auto* resp_subnet = dev->mutable_ipv4_subnet();
585 resp_subnet->set_base_addr(subnet->BaseAddress());
586 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900587 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900588 if (!subnet) {
589 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
590 writer.AppendProtoAsArrayOfBytes(response);
591 return dbus_response;
592 }
593 resp_subnet = response.mutable_container_subnet();
594 resp_subnet->set_base_addr(subnet->BaseAddress());
595 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900596
597 writer.AppendProtoAsArrayOfBytes(response);
598 return dbus_response;
599}
600
601std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
602 dbus::MethodCall* method_call) {
603 LOG(INFO) << "Termina VM shutting down";
604
605 std::unique_ptr<dbus::Response> dbus_response(
606 dbus::Response::FromMethodCall(method_call));
607
608 dbus::MessageReader reader(method_call);
609 dbus::MessageWriter writer(dbus_response.get());
610
611 patchpanel::TerminaVmShutdownRequest request;
612 patchpanel::TerminaVmShutdownResponse response;
613
614 if (!reader.PopArrayOfBytesAsProto(&request)) {
615 LOG(ERROR) << "Unable to parse request";
616 writer.AppendProtoAsArrayOfBytes(response);
617 return dbus_response;
618 }
619
Garrick Evans51d5b552020-01-30 10:42:06 +0900620 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
621
622 writer.AppendProtoAsArrayOfBytes(response);
623 return dbus_response;
624}
625
626std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
627 dbus::MethodCall* method_call) {
628 LOG(INFO) << "Plugin VM starting up";
629
630 std::unique_ptr<dbus::Response> dbus_response(
631 dbus::Response::FromMethodCall(method_call));
632
633 dbus::MessageReader reader(method_call);
634 dbus::MessageWriter writer(dbus_response.get());
635
636 patchpanel::PluginVmStartupRequest request;
637 patchpanel::PluginVmStartupResponse response;
638
639 if (!reader.PopArrayOfBytesAsProto(&request)) {
640 LOG(ERROR) << "Unable to parse request";
641 writer.AppendProtoAsArrayOfBytes(response);
642 return dbus_response;
643 }
644
Garrick Evans08fb34b2020-02-20 10:50:17 +0900645 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900646 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900647 LOG(ERROR) << "Failed to start Plugin VM network service";
648 writer.AppendProtoAsArrayOfBytes(response);
649 return dbus_response;
650 }
651
652 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
653 if (!tap) {
654 LOG(DFATAL) << "TAP device missing";
655 writer.AppendProtoAsArrayOfBytes(response);
656 return dbus_response;
657 }
658
Garrick Evans51d5b552020-01-30 10:42:06 +0900659 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900660 dev->set_ifname(tap->host_ifname());
661 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900662 if (!subnet) {
663 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
664 writer.AppendProtoAsArrayOfBytes(response);
665 return dbus_response;
666 }
667 auto* resp_subnet = dev->mutable_ipv4_subnet();
668 resp_subnet->set_base_addr(subnet->BaseAddress());
669 resp_subnet->set_prefix_len(subnet->PrefixLength());
670
671 writer.AppendProtoAsArrayOfBytes(response);
672 return dbus_response;
673}
674
675std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
676 dbus::MethodCall* method_call) {
677 LOG(INFO) << "Plugin VM shutting down";
678
679 std::unique_ptr<dbus::Response> dbus_response(
680 dbus::Response::FromMethodCall(method_call));
681
682 dbus::MessageReader reader(method_call);
683 dbus::MessageWriter writer(dbus_response.get());
684
685 patchpanel::PluginVmShutdownRequest request;
686 patchpanel::PluginVmShutdownResponse response;
687
688 if (!reader.PopArrayOfBytesAsProto(&request)) {
689 LOG(ERROR) << "Unable to parse request";
690 writer.AppendProtoAsArrayOfBytes(response);
691 return dbus_response;
692 }
693
694 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900695
696 writer.AppendProtoAsArrayOfBytes(response);
697 return dbus_response;
698}
699
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900700std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
701 dbus::MethodCall* method_call) {
702 std::unique_ptr<dbus::Response> dbus_response(
703 dbus::Response::FromMethodCall(method_call));
704
705 dbus::MessageReader reader(method_call);
706 dbus::MessageWriter writer(dbus_response.get());
707
708 patchpanel::SetVpnIntentRequest request;
709 patchpanel::SetVpnIntentResponse response;
710
711 bool success = reader.PopArrayOfBytesAsProto(&request);
712 if (!success) {
713 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
714 // Do not return yet to make sure we close the received fd.
715 }
716
717 base::ScopedFD client_socket;
718 reader.PopFileDescriptor(&client_socket);
719
720 if (success)
721 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
722
723 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900724
725 writer.AppendProtoAsArrayOfBytes(response);
726 return dbus_response;
727}
728
729std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
730 dbus::MethodCall* method_call) {
731 std::unique_ptr<dbus::Response> dbus_response(
732 dbus::Response::FromMethodCall(method_call));
733
734 dbus::MessageReader reader(method_call);
735 dbus::MessageWriter writer(dbus_response.get());
736
737 patchpanel::ConnectNamespaceRequest request;
738 patchpanel::ConnectNamespaceResponse response;
739
Hugo Benichicc6850f2020-01-17 13:26:06 +0900740 bool success = true;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900741 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900742 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
743 // Do not return yet to make sure we close the received fd and
744 // validate other arguments.
745 success = false;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900746 }
747
Hugo Benichicc6850f2020-01-17 13:26:06 +0900748 base::ScopedFD client_fd;
749 reader.PopFileDescriptor(&client_fd);
750 if (!client_fd.is_valid()) {
751 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
752 success = false;
753 }
754
755 pid_t pid = request.pid();
756 {
757 ScopedNS ns(pid);
758 if (!ns.IsValid()) {
759 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
760 success = false;
761 }
762 }
763
764 const std::string& outbound_ifname = request.outbound_physical_device();
765 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
766 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
767 << outbound_ifname;
768 success = false;
769 }
770
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900771 if (success)
772 ConnectNamespace(std::move(client_fd), request, response);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900773
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900774 writer.AppendProtoAsArrayOfBytes(response);
775 return dbus_response;
776}
777
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900778std::unique_ptr<dbus::Response> Manager::OnModifyPortRule(
779 dbus::MethodCall* method_call) {
780 std::unique_ptr<dbus::Response> dbus_response(
781 dbus::Response::FromMethodCall(method_call));
782
783 dbus::MessageReader reader(method_call);
784 dbus::MessageWriter writer(dbus_response.get());
785
786 patchpanel::ModifyPortRuleRequest request;
787 patchpanel::ModifyPortRuleResponse response;
788
789 if (!reader.PopArrayOfBytesAsProto(&request)) {
790 LOG(ERROR) << "Unable to parse ModifyPortRequest";
791 writer.AppendProtoAsArrayOfBytes(response);
792 return dbus_response;
793 }
794
795 // TODO(b/160129667): Handle ModifyPortRule request.
796 writer.AppendProtoAsArrayOfBytes(response);
797 return dbus_response;
798}
799
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900800void Manager::ConnectNamespace(
801 base::ScopedFD client_fd,
802 const patchpanel::ConnectNamespaceRequest& request,
803 patchpanel::ConnectNamespaceResponse& response) {
804 std::unique_ptr<Subnet> subnet =
805 addr_mgr_.AllocateIPv4Subnet(AddressManager::Guest::MINIJAIL_NETNS);
806 if (!subnet) {
807 LOG(ERROR) << "ConnectNamespaceRequest: exhausted IPv4 subnet space";
808 return;
809 }
810
811 const std::string ifname_id = std::to_string(connected_namespaces_next_id_);
Hugo Benichi33860d72020-07-09 16:34:01 +0900812 const std::string netns_name = "connected_netns_" + ifname_id;
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900813 const std::string host_ifname = "arc_ns" + ifname_id;
814 const std::string client_ifname = "veth" + ifname_id;
Hugo Benichie8758b52020-04-03 14:49:01 +0900815 const uint32_t host_ipv4_addr = subnet->AddressAtOffset(0);
816 const uint32_t client_ipv4_addr = subnet->AddressAtOffset(1);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900817
Hugo Benichie8758b52020-04-03 14:49:01 +0900818 // Veth interface configuration and client routing configuration:
Hugo Benichi33860d72020-07-09 16:34:01 +0900819 // - attach a name to the client namespace.
820 // - create veth pair across the current namespace and the client namespace.
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900821 // - configure IPv4 address on remote veth inside client namespace.
Hugo Benichie8758b52020-04-03 14:49:01 +0900822 // - configure IPv4 address on local veth inside host namespace.
823 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichie8758b52020-04-03 14:49:01 +0900824 pid_t pid = request.pid();
Hugo Benichi33860d72020-07-09 16:34:01 +0900825 if (!datapath_->NetnsAttachName(netns_name, pid)) {
826 LOG(ERROR) << "ConnectNamespaceRequest: failed to attach name "
827 << netns_name << " to namespace pid " << pid;
828 return;
829 }
830 if (!datapath_->ConnectVethPair(pid, netns_name, host_ifname, client_ifname,
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900831 addr_mgr_.GenerateMacAddress(),
832 client_ipv4_addr, subnet->PrefixLength(),
833 false /* enable_multicast */)) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900834 LOG(ERROR) << "ConnectNamespaceRequest: failed to create veth pair for "
835 "namespace pid "
836 << pid;
Hugo Benichi33860d72020-07-09 16:34:01 +0900837 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900838 return;
839 }
840 if (!datapath_->ConfigureInterface(
841 host_ifname, addr_mgr_.GenerateMacAddress(), host_ipv4_addr,
842 subnet->PrefixLength(), true /* link up */,
843 false /* enable_multicast */)) {
844 LOG(ERROR) << "ConnectNamespaceRequest: cannot configure host interface "
845 << host_ifname;
846 datapath_->RemoveInterface(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900847 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900848 return;
849 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900850 bool peer_route_setup_success;
Hugo Benichie8758b52020-04-03 14:49:01 +0900851 {
852 ScopedNS ns(pid);
Hugo Benichi33860d72020-07-09 16:34:01 +0900853 peer_route_setup_success =
854 ns.IsValid() &&
855 datapath_->AddIPv4Route(host_ipv4_addr, INADDR_ANY, INADDR_ANY);
856 }
857 if (!peer_route_setup_success) {
858 LOG(ERROR) << "ConnectNamespaceRequest: failed to add default /0 route to "
859 << host_ifname << " inside namespace pid " << pid;
860 datapath_->RemoveInterface(host_ifname);
861 datapath_->NetnsDeleteName(netns_name);
862 return;
Hugo Benichie8758b52020-04-03 14:49:01 +0900863 }
864
865 // Host namespace routing configuration
866 // - ingress: add route to client subnet via |host_ifname|.
867 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
868 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
869 // Note that by default unsolicited ingress traffic is not forwarded to the
870 // client namespace unless the client specifically set port forwarding
871 // through permission_broker DBus APIs.
872 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
873 // both ways between client namespace and other guest containers and VMs.
874 // TODO(hugobenichi) If outbound_physical_device is defined, then set strong
875 // routing to that interface routing table.
876 if (!datapath_->AddIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
877 subnet->Netmask())) {
878 LOG(ERROR)
879 << "ConnectNamespaceRequest: failed to set route to client namespace";
880 datapath_->RemoveInterface(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900881 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900882 return;
883 }
884 if (!datapath_->AddOutboundIPv4(host_ifname)) {
885 LOG(ERROR) << "ConnectNamespaceRequest: failed to allow FORWARD for "
886 "traffic outgoing from "
887 << host_ifname;
888 datapath_->RemoveInterface(host_ifname);
889 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
890 subnet->Netmask());
Hugo Benichi33860d72020-07-09 16:34:01 +0900891 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900892 return;
893 }
894 if (!datapath_->AddOutboundIPv4SNATMark(host_ifname)) {
895 LOG(ERROR) << "ConnectNamespaceRequest: failed to set SNAT for traffic "
896 "outgoing from "
897 << host_ifname;
898 datapath_->RemoveInterface(host_ifname);
899 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
900 subnet->Netmask());
901 datapath_->RemoveOutboundIPv4(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900902 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900903 return;
904 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900905
Hugo Benichi7352ad92020-04-07 16:11:59 +0900906 // Dup the client fd into our own: this guarantees that the fd number will
907 // be stable and tied to the actual kernel resources used by the client.
908 base::ScopedFD local_client_fd(dup(client_fd.get()));
909 if (!local_client_fd.is_valid()) {
910 PLOG(ERROR) << "ConnectNamespaceRequest: failed to dup() client fd";
Hugo Benichie8758b52020-04-03 14:49:01 +0900911 datapath_->RemoveInterface(host_ifname);
912 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
913 subnet->Netmask());
914 datapath_->RemoveOutboundIPv4(host_ifname);
915 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900916 datapath_->NetnsDeleteName(netns_name);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900917 return;
918 }
919
920 // Add the dupe fd to the epoll watcher.
921 // TODO(hugobenichi) Find a way to reuse base::FileDescriptorWatcher for
922 // listening to EPOLLHUP.
923 struct epoll_event epevent;
924 epevent.events = EPOLLIN; // EPOLLERR | EPOLLHUP are always waited for.
925 epevent.data.fd = local_client_fd.get();
926 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_ADD,
927 local_client_fd.get(), &epevent) != 0) {
928 PLOG(ERROR) << "ConnectNamespaceResponse: epoll_ctl(EPOLL_CTL_ADD) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900929 datapath_->RemoveInterface(host_ifname);
930 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
931 subnet->Netmask());
932 datapath_->RemoveOutboundIPv4(host_ifname);
933 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900934 datapath_->NetnsDeleteName(netns_name);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900935 return;
936 }
937
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900938 // Prepare the response before storing ConnectNamespaceInfo.
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900939 response.set_peer_ifname(client_ifname);
940 response.set_peer_ipv4_address(host_ipv4_addr);
941 response.set_host_ifname(host_ifname);
942 response.set_host_ipv4_address(client_ipv4_addr);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900943 auto* response_subnet = response.mutable_ipv4_subnet();
944 response_subnet->set_base_addr(subnet->BaseAddress());
945 response_subnet->set_prefix_len(subnet->PrefixLength());
946
947 // Store ConnectNamespaceInfo
948 connected_namespaces_next_id_++;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900949 int fdkey = local_client_fd.release();
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900950 connected_namespaces_[fdkey] = {};
951 ConnectNamespaceInfo& ns_info = connected_namespaces_[fdkey];
952 ns_info.pid = request.pid();
Hugo Benichi33860d72020-07-09 16:34:01 +0900953 ns_info.netns_name = std::move(netns_name);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900954 ns_info.outbound_ifname = request.outbound_physical_device();
955 ns_info.host_ifname = std::move(host_ifname);
956 ns_info.client_ifname = std::move(client_ifname);
957 ns_info.client_subnet = std::move(subnet);
958
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900959 LOG(INFO) << "Connected network namespace " << ns_info;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900960
961 if (connected_namespaces_.size() == 1) {
962 LOG(INFO) << "Starting ConnectNamespace client fds monitoring";
963 CheckConnectedNamespaces();
964 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900965}
966
967void Manager::DisconnectNamespace(int client_fd) {
968 auto it = connected_namespaces_.find(client_fd);
969 if (it == connected_namespaces_.end()) {
970 LOG(ERROR) << "No ConnectNamespaceInfo found for client_fd " << client_fd;
971 return;
972 }
973
Hugo Benichi7352ad92020-04-07 16:11:59 +0900974 // Remove the client fd dupe from the epoll watcher and close it.
975 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL, client_fd,
Hugo Benichie8758b52020-04-03 14:49:01 +0900976 nullptr) != 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900977 PLOG(ERROR) << "DisconnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900978 if (close(client_fd) < 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900979 PLOG(ERROR) << "DisconnectNamespace: close(client_fd) failed";
Hugo Benichi7352ad92020-04-07 16:11:59 +0900980
Hugo Benichie8758b52020-04-03 14:49:01 +0900981 // Destroy the interface configuration and routing configuration:
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900982 // - destroy veth pair.
Hugo Benichie8758b52020-04-03 14:49:01 +0900983 // - remove forwarding rules on host namespace.
984 // - remove SNAT marking rule on host namespace.
Hugo Benichi33860d72020-07-09 16:34:01 +0900985 // Delete the network namespace attached to the client namespace.
Hugo Benichie8758b52020-04-03 14:49:01 +0900986 // Note that the default route set inside the client namespace by patchpanel
987 // is not destroyed: it is assumed the client will also teardown its
988 // namespace if it triggered DisconnectNamespace.
989 datapath_->RemoveInterface(it->second.host_ifname);
990 datapath_->RemoveOutboundIPv4(it->second.host_ifname);
991 datapath_->RemoveOutboundIPv4SNATMark(it->second.host_ifname);
992 datapath_->DeleteIPv4Route(it->second.client_subnet->AddressAtOffset(0),
993 it->second.client_subnet->BaseAddress(),
994 it->second.client_subnet->Netmask());
Hugo Benichi33860d72020-07-09 16:34:01 +0900995 datapath_->NetnsDeleteName(it->second.netns_name);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900996
997 LOG(INFO) << "Disconnected network namespace " << it->second;
998
999 // This release the allocated IPv4 subnet.
1000 connected_namespaces_.erase(it);
1001}
1002
Hugo Benichi7352ad92020-04-07 16:11:59 +09001003// TODO(hugobenichi) Generalize this check to all resources created by
1004// patchpanel on behalf of a remote client.
1005void Manager::CheckConnectedNamespaces() {
1006 int max_event = 10;
1007 struct epoll_event epevents[max_event];
1008 int nready = epoll_wait(connected_namespaces_epollfd_, epevents, max_event,
1009 0 /* do not block */);
1010 if (nready < 0)
1011 PLOG(ERROR) << "CheckConnectedNamespaces: epoll_wait(0) failed";
1012
1013 for (int i = 0; i < nready; i++)
1014 if (epevents[i].events & (EPOLLHUP | EPOLLERR))
1015 DisconnectNamespace(epevents[i].data.fd);
1016
1017 if (connected_namespaces_.empty()) {
1018 LOG(INFO) << "Stopping ConnectNamespace client fds monitoring";
1019 return;
1020 }
1021
Qijiang Fan2d7aeb42020-05-19 02:06:39 +09001022 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Hugo Benichi7352ad92020-04-07 16:11:59 +09001023 FROM_HERE,
1024 base::Bind(&Manager::CheckConnectedNamespaces,
Hugo Benichie8758b52020-04-03 14:49:01 +09001025 weak_factory_.GetWeakPtr()),
Hugo Benichi7352ad92020-04-07 16:11:59 +09001026 kConnectNamespaceCheckInterval);
1027}
1028
Garrick Evanse94a14e2019-11-11 10:32:13 +09001029void Manager::SendGuestMessage(const GuestMessage& msg) {
Garrick Evans96e03042019-05-28 14:30:52 +09001030 IpHelperMessage ipm;
1031 *ipm.mutable_guest_message() = msg;
Garrick Evans96e03042019-05-28 14:30:52 +09001032 adb_proxy_->SendMessage(ipm);
Garrick Evanse94a14e2019-11-11 10:32:13 +09001033 mcast_proxy_->SendMessage(ipm);
1034 nd_proxy_->SendMessage(ipm);
Garrick Evans96e03042019-05-28 14:30:52 +09001035}
1036
Garrick Evans4ac09852020-01-16 14:09:22 +09001037void Manager::StartForwarding(const std::string& ifname_physical,
1038 const std::string& ifname_virtual,
Garrick Evans4ac09852020-01-16 14:09:22 +09001039 bool ipv6,
1040 bool multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001041 if (ifname_physical.empty() || ifname_virtual.empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001042 return;
1043
1044 IpHelperMessage ipm;
1045 DeviceMessage* msg = ipm.mutable_device_message();
1046 msg->set_dev_ifname(ifname_physical);
Garrick Evans4ac09852020-01-16 14:09:22 +09001047 msg->set_br_ifname(ifname_virtual);
1048
1049 if (ipv6) {
1050 LOG(INFO) << "Starting IPv6 forwarding from " << ifname_physical << " to "
1051 << ifname_virtual;
1052
1053 if (!datapath_->AddIPv6Forwarding(ifname_physical, ifname_virtual)) {
1054 LOG(ERROR) << "Failed to setup iptables forwarding rule for IPv6 from "
1055 << ifname_physical << " to " << ifname_virtual;
1056 }
1057 if (!datapath_->MaskInterfaceFlags(ifname_physical, IFF_ALLMULTI)) {
1058 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1059 << ifname_physical;
1060 }
1061 if (!datapath_->MaskInterfaceFlags(ifname_virtual, IFF_ALLMULTI)) {
1062 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1063 << ifname_virtual;
1064 }
1065 nd_proxy_->SendMessage(ipm);
1066 }
1067
1068 if (multicast) {
1069 LOG(INFO) << "Starting multicast forwarding from " << ifname_physical
1070 << " to " << ifname_virtual;
1071 mcast_proxy_->SendMessage(ipm);
1072 }
1073}
1074
1075void Manager::StopForwarding(const std::string& ifname_physical,
1076 const std::string& ifname_virtual,
1077 bool ipv6,
1078 bool multicast) {
1079 if (ifname_physical.empty())
1080 return;
1081
1082 IpHelperMessage ipm;
1083 DeviceMessage* msg = ipm.mutable_device_message();
1084 msg->set_dev_ifname(ifname_physical);
1085 msg->set_teardown(true);
Taoyu Li7dca19a2020-03-16 16:27:07 +09001086 if (!ifname_virtual.empty()) {
1087 msg->set_br_ifname(ifname_virtual);
1088 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001089
1090 if (ipv6) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001091 if (ifname_virtual.empty()) {
1092 LOG(INFO) << "Stopping IPv6 forwarding on " << ifname_physical;
1093 } else {
1094 LOG(INFO) << "Stopping IPv6 forwarding from " << ifname_physical << " to "
1095 << ifname_virtual;
1096 datapath_->RemoveIPv6Forwarding(ifname_physical, ifname_virtual);
1097 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001098 nd_proxy_->SendMessage(ipm);
1099 }
1100
1101 if (multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001102 if (ifname_virtual.empty()) {
1103 LOG(INFO) << "Stopping multicast forwarding on " << ifname_physical;
1104 } else {
1105 LOG(INFO) << "Stopping multicast forwarding from " << ifname_physical
1106 << " to " << ifname_virtual;
1107 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001108 mcast_proxy_->SendMessage(ipm);
1109 }
1110}
1111
Garrick Evans4ac09852020-01-16 14:09:22 +09001112void Manager::OnDeviceMessageFromNDProxy(const DeviceMessage& msg) {
1113 LOG_IF(DFATAL, msg.dev_ifname().empty())
1114 << "Received DeviceMessage w/ empty dev_ifname";
1115
1116 if (!datapath_->AddIPv6HostRoute(msg.dev_ifname(), msg.guest_ip6addr(),
1117 128)) {
1118 LOG(WARNING) << "Failed to setup the IPv6 route for interface "
1119 << msg.dev_ifname();
1120 }
1121}
1122
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001123std::ostream& operator<<(std::ostream& stream,
1124 const Manager::ConnectNamespaceInfo& ns_info) {
1125 stream << "{ pid: " << ns_info.pid;
1126 if (!ns_info.outbound_ifname.empty()) {
1127 stream << ", outbound_ifname: " << ns_info.outbound_ifname;
1128 }
1129 stream << ", host_ifname: " << ns_info.host_ifname
1130 << ", client_ifname: " << ns_info.client_ifname
1131 << ", subnet: " << ns_info.client_subnet->ToCidrString() << '}';
1132 return stream;
1133}
1134
Garrick Evans3388a032020-03-24 11:25:55 +09001135} // namespace patchpanel