blob: a31fe6fd5a6d8b393410aa3725b5d759ae9231b7 [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
Garrick Evansf5862122020-03-16 09:13:45 +090043constexpr char kArcVmMultinetFeatureName[] = "ARCVM Multinet";
44constexpr int kArcVmMultinetMinAndroidSdkVersion = 29; // R DEV
45constexpr int kArcVmMultinetMinChromeMilestone = 99; // DISABLED
46
Hugo Benichi7352ad92020-04-07 16:11:59 +090047// Time interval between epoll checks on file descriptors committed by callers
48// of ConnectNamespace DBus API.
49constexpr const base::TimeDelta kConnectNamespaceCheckInterval =
50 base::TimeDelta::FromSeconds(30);
51
Garrick Evans08843932019-09-17 14:41:08 +090052// Passes |method_call| to |handler| and passes the response to
53// |response_sender|. If |handler| returns nullptr, an empty response is
54// created and sent.
55void HandleSynchronousDBusMethodCall(
56 base::Callback<std::unique_ptr<dbus::Response>(dbus::MethodCall*)> handler,
57 dbus::MethodCall* method_call,
58 dbus::ExportedObject::ResponseSender response_sender) {
59 std::unique_ptr<dbus::Response> response = handler.Run(method_call);
60 if (!response)
61 response = dbus::Response::FromMethodCall(method_call);
62 response_sender.Run(std::move(response));
63}
64
65} // namespace
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070066
Taoyu Lice7caa62019-10-01 15:43:33 +090067Manager::Manager(std::unique_ptr<HelperProcess> adb_proxy,
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090068 std::unique_ptr<HelperProcess> mcast_proxy,
Garrick Evans1f5a3612019-11-08 12:59:03 +090069 std::unique_ptr<HelperProcess> nd_proxy)
Garrick Evans3915af32019-07-25 15:44:34 +090070 : adb_proxy_(std::move(adb_proxy)),
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090071 mcast_proxy_(std::move(mcast_proxy)),
Garrick Evans4ee5ce22020-03-18 07:05:17 +090072 nd_proxy_(std::move(nd_proxy)) {
Taoyu Li179dcc62019-10-17 11:21:08 +090073 runner_ = std::make_unique<MinijailedProcessRunner>();
74 datapath_ = std::make_unique<Datapath>(runner_.get());
Hugo Benichi7352ad92020-04-07 16:11:59 +090075 connected_namespaces_epollfd_ = epoll_create(1 /* size */);
Taoyu Li179dcc62019-10-17 11:21:08 +090076}
Long Chengd4415582019-09-24 19:16:09 +000077
Garrick Evans207e7482019-12-16 11:54:36 +090078Manager::~Manager() {
79 OnShutdown(nullptr);
80}
81
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +090082std::map<const std::string, bool> Manager::cached_feature_enabled_ = {};
83
84bool Manager::ShouldEnableFeature(
85 int min_android_sdk_version,
86 int min_chrome_milestone,
87 const std::vector<std::string>& supported_boards,
88 const std::string& feature_name) {
89 static const char kLsbReleasePath[] = "/etc/lsb-release";
90
91 const auto& cached_result = cached_feature_enabled_.find(feature_name);
92 if (cached_result != cached_feature_enabled_.end())
93 return cached_result->second;
94
95 auto check = [min_android_sdk_version, min_chrome_milestone,
96 &supported_boards, &feature_name]() {
97 brillo::KeyValueStore store;
98 if (!store.Load(base::FilePath(kLsbReleasePath))) {
99 LOG(ERROR) << "Could not read lsb-release";
100 return false;
101 }
102
103 std::string value;
104 if (!store.GetString("CHROMEOS_ARC_ANDROID_SDK_VERSION", &value)) {
105 LOG(ERROR) << feature_name
106 << " disabled - cannot determine Android SDK version";
107 return false;
108 }
109 int ver = 0;
110 if (!base::StringToInt(value.c_str(), &ver)) {
111 LOG(ERROR) << feature_name << " disabled - invalid Android SDK version";
112 return false;
113 }
114 if (ver < min_android_sdk_version) {
115 LOG(INFO) << feature_name << " disabled for Android SDK " << value;
116 return false;
117 }
118
119 if (!store.GetString("CHROMEOS_RELEASE_CHROME_MILESTONE", &value)) {
120 LOG(ERROR) << feature_name
121 << " disabled - cannot determine ChromeOS milestone";
122 return false;
123 }
124 if (!base::StringToInt(value.c_str(), &ver)) {
125 LOG(ERROR) << feature_name << " disabled - invalid ChromeOS milestone";
126 return false;
127 }
128 if (ver < min_chrome_milestone) {
129 LOG(INFO) << feature_name << " disabled for ChromeOS milestone " << value;
130 return false;
131 }
132
133 if (!store.GetString("CHROMEOS_RELEASE_BOARD", &value)) {
134 LOG(ERROR) << feature_name << " disabled - cannot determine board";
135 return false;
136 }
137 if (!supported_boards.empty() &&
138 std::find(supported_boards.begin(), supported_boards.end(), value) ==
139 supported_boards.end()) {
140 LOG(INFO) << feature_name << " disabled for board " << value;
141 return false;
142 }
143 return true;
144 };
145
146 bool result = check();
147 cached_feature_enabled_.emplace(feature_name, result);
148 return result;
149}
150
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700151int Manager::OnInit() {
Garrick Evans54861622019-07-19 09:05:09 +0900152 prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800153
154 // Handle subprocess lifecycle.
155 process_reaper_.Register(this);
Hugo Benichi935eca92018-07-03 13:47:24 +0900156
157 CHECK(process_reaper_.WatchForChild(
Garrick Evans96e03042019-05-28 14:30:52 +0900158 FROM_HERE, adb_proxy_->pid(),
159 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
160 adb_proxy_->pid())))
161 << "Failed to watch adb-proxy child process";
Taoyu Liaf944c92019-10-01 12:22:31 +0900162 CHECK(process_reaper_.WatchForChild(
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900163 FROM_HERE, mcast_proxy_->pid(),
164 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
165 nd_proxy_->pid())))
166 << "Failed to watch multicast-proxy child process";
167 CHECK(process_reaper_.WatchForChild(
Taoyu Liaf944c92019-10-01 12:22:31 +0900168 FROM_HERE, nd_proxy_->pid(),
169 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
170 nd_proxy_->pid())))
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900171 << "Failed to watch nd-proxy child process";
Garrick Evans96e03042019-05-28 14:30:52 +0900172
Garrick Evans49879532018-12-03 13:15:36 +0900173 // Run after Daemon::OnInit().
hschamf9546312020-04-14 15:12:40 +0900174 base::ThreadTaskRunnerHandle::Get()->PostTask(
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700175 FROM_HERE,
176 base::Bind(&Manager::InitialSetup, weak_factory_.GetWeakPtr()));
177
178 return DBusDaemon::OnInit();
179}
180
181void Manager::InitialSetup() {
Garrick Evans08843932019-09-17 14:41:08 +0900182 LOG(INFO) << "Setting up DBus service interface";
183 dbus_svc_path_ = bus_->GetExportedObject(
184 dbus::ObjectPath(patchpanel::kPatchPanelServicePath));
185 if (!dbus_svc_path_) {
186 LOG(FATAL) << "Failed to export " << patchpanel::kPatchPanelServicePath
187 << " object";
188 }
189
190 using ServiceMethod =
191 std::unique_ptr<dbus::Response> (Manager::*)(dbus::MethodCall*);
192 const std::map<const char*, ServiceMethod> kServiceMethods = {
193 {patchpanel::kArcStartupMethod, &Manager::OnArcStartup},
194 {patchpanel::kArcShutdownMethod, &Manager::OnArcShutdown},
195 {patchpanel::kArcVmStartupMethod, &Manager::OnArcVmStartup},
196 {patchpanel::kArcVmShutdownMethod, &Manager::OnArcVmShutdown},
Garrick Evans47c19272019-11-21 10:58:21 +0900197 {patchpanel::kTerminaVmStartupMethod, &Manager::OnTerminaVmStartup},
198 {patchpanel::kTerminaVmShutdownMethod, &Manager::OnTerminaVmShutdown},
Garrick Evans51d5b552020-01-30 10:42:06 +0900199 {patchpanel::kPluginVmStartupMethod, &Manager::OnPluginVmStartup},
200 {patchpanel::kPluginVmShutdownMethod, &Manager::OnPluginVmShutdown},
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900201 {patchpanel::kSetVpnIntentMethod, &Manager::OnSetVpnIntent},
Hugo Benichib56b77c2020-01-15 16:00:56 +0900202 {patchpanel::kConnectNamespaceMethod, &Manager::OnConnectNamespace},
Garrick Evans08843932019-09-17 14:41:08 +0900203 };
204
205 for (const auto& kv : kServiceMethods) {
206 if (!dbus_svc_path_->ExportMethodAndBlock(
207 patchpanel::kPatchPanelInterface, kv.first,
208 base::Bind(&HandleSynchronousDBusMethodCall,
209 base::Bind(kv.second, base::Unretained(this))))) {
210 LOG(FATAL) << "Failed to export method " << kv.first;
211 }
212 }
213
214 if (!bus_->RequestOwnershipAndBlock(patchpanel::kPatchPanelServiceName,
215 dbus::Bus::REQUIRE_PRIMARY)) {
216 LOG(FATAL) << "Failed to take ownership of "
217 << patchpanel::kPatchPanelServiceName;
218 }
219 LOG(INFO) << "DBus service interface ready";
220
Taoyu Li6d479442019-12-09 13:02:29 +0900221 auto& runner = datapath_->runner();
Garrick Evans7cf8c542020-05-25 09:50:17 +0900222 // Enable IPv4 packet forwarding
223 if (runner.sysctl_w("net.ipv4.ip_forward", "1") != 0) {
224 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
225 << " Guest connectivity will not work correctly.";
226 }
Garrick Evans28d194e2019-12-17 10:22:28 +0900227 // Limit local port range: Android owns 47104-61000.
228 // TODO(garrick): The original history behind this tweak is gone. Some
229 // investigation is needed to see if it is still applicable.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900230 if (runner.sysctl_w("net.ipv4.ip_local_port_range", "32768 47103") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900231 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
232 << " apps may not work correctly.";
233 }
Taoyu Li6d479442019-12-09 13:02:29 +0900234 // Enable IPv6 packet forarding
Garrick Evans8e8e3472020-01-23 14:03:50 +0900235 if (runner.sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0) {
Taoyu Li6d479442019-12-09 13:02:29 +0900236 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
237 << " IPv6 functionality may be broken.";
238 }
239 // Kernel proxy_ndp is only needed for legacy IPv6 configuration
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +0900240 if (!ShouldEnableFeature(kNDProxyMinAndroidSdkVersion,
Garrick Evansf5862122020-03-16 09:13:45 +0900241 kNDProxyMinChromeMilestone, {},
242 kNDProxyFeatureName) &&
Garrick Evans8e8e3472020-01-23 14:03:50 +0900243 runner.sysctl_w("net.ipv6.conf.all.proxy_ndp", "1") != 0) {
Taoyu Li6d479442019-12-09 13:02:29 +0900244 LOG(ERROR) << "Failed to update net.ipv6.conf.all.proxy_ndp."
245 << " IPv6 functionality may be broken.";
246 }
247
Garrick Evansd291af62020-05-25 10:39:06 +0900248 if (!datapath_->AddSNATMarkRules()) {
249 LOG(ERROR) << "Failed to install SNAT mark rules."
250 << " Guest connectivity may be broken.";
251 }
252 if (!datapath_->AddForwardEstablishedRule()) {
253 LOG(ERROR) << "Failed to install forwarding rule for established"
254 << " connections.";
255 }
256
Garrick Evansff6e37f2020-05-25 10:54:47 +0900257 // TODO(chromium:898210): Move interface-specific masquerading setup to shill;
258 // such that we can better set up the masquerade rules based on connection
259 // type rather than interface names.
260 if (!datapath_->AddInterfaceSNAT("wwan+")) {
261 LOG(ERROR) << "Failed to set up wifi masquerade";
262 }
263
Garrick Evansc50426b2020-05-25 11:00:55 +0900264 if (!datapath_->AddOutboundIPv4SNATMark("vmtap+")) {
265 LOG(ERROR) << "Failed to set up NAT for TAP devices."
266 << " Guest connectivity may be broken.";
267 }
268
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900269 routing_svc_ = std::make_unique<RoutingService>();
270
Garrick Evans4ac09852020-01-16 14:09:22 +0900271 nd_proxy_->RegisterDeviceMessageHandler(base::Bind(
272 &Manager::OnDeviceMessageFromNDProxy, weak_factory_.GetWeakPtr()));
273
Garrick Evans69b85872020-02-04 11:40:26 +0900274 shill_client_ = std::make_unique<ShillClient>(bus_);
Garrick Evans1b1f67c2020-02-04 16:21:25 +0900275 auto* const forwarder = static_cast<TrafficForwarder*>(this);
Garrick Evans5d55f5e2019-07-17 15:28:10 +0900276
Garrick Evansf5862122020-03-16 09:13:45 +0900277 arc_svc_ = std::make_unique<ArcService>(
278 shill_client_.get(), datapath_.get(), &addr_mgr_, forwarder,
279 ShouldEnableFeature(kArcVmMultinetMinAndroidSdkVersion,
280 kArcVmMultinetMinChromeMilestone, {},
281 kArcVmMultinetFeatureName));
Garrick Evans1b1f67c2020-02-04 16:21:25 +0900282 cros_svc_ = std::make_unique<CrostiniService>(shill_client_.get(), &addr_mgr_,
283 datapath_.get(), forwarder);
Jie Jiang01c1a2e2020-04-08 20:58:30 +0900284 network_monitor_svc_ =
285 std::make_unique<NetworkMonitorService>(shill_client_.get());
286 network_monitor_svc_->Start();
Taoyu Liaf944c92019-10-01 12:22:31 +0900287
288 nd_proxy_->Listen();
Long Chengd4415582019-09-24 19:16:09 +0000289}
Garrick Evans49879532018-12-03 13:15:36 +0900290
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800291void Manager::OnShutdown(int* exit_code) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900292 LOG(INFO) << "Shutting down and cleaning up";
Garrick Evans207e7482019-12-16 11:54:36 +0900293 cros_svc_.reset();
294 arc_svc_.reset();
Hugo Benichi7352ad92020-04-07 16:11:59 +0900295 close(connected_namespaces_epollfd_);
Hugo Benichie8758b52020-04-03 14:49:01 +0900296 // Tear down any remaining connected namespace.
297 std::vector<int> connected_namespaces_fdkeys;
298 for (const auto& kv : connected_namespaces_)
299 connected_namespaces_fdkeys.push_back(kv.first);
300 for (const int fdkey : connected_namespaces_fdkeys)
301 DisconnectNamespace(fdkey);
Garrick Evans28d194e2019-12-17 10:22:28 +0900302
Garrick Evansc50426b2020-05-25 11:00:55 +0900303 datapath_->RemoveOutboundIPv4SNATMark("vmtap+");
Garrick Evansff6e37f2020-05-25 10:54:47 +0900304 datapath_->RemoveInterfaceSNAT("wwan+");
Garrick Evansd291af62020-05-25 10:39:06 +0900305 datapath_->RemoveForwardEstablishedRule();
306 datapath_->RemoveSNATMarkRules();
307
Garrick Evans7cf8c542020-05-25 09:50:17 +0900308 auto& runner = datapath_->runner();
Garrick Evans28d194e2019-12-17 10:22:28 +0900309 // Restore original local port range.
310 // TODO(garrick): The original history behind this tweak is gone. Some
311 // investigation is needed to see if it is still applicable.
Garrick Evans7cf8c542020-05-25 09:50:17 +0900312 if (runner.sysctl_w("net.ipv4.ip_local_port_range", "32768 61000") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900313 LOG(ERROR) << "Failed to restore local port range";
314 }
Garrick Evans7cf8c542020-05-25 09:50:17 +0900315 // Disable packet forwarding
316 if (runner.sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0) {
317 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
318 }
319 if (runner.sysctl_w("net.ipv4.ip_forward", "0") != 0) {
320 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
321 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800322}
323
Garrick Evans4c042572019-12-17 13:42:25 +0900324void Manager::OnSubprocessExited(pid_t pid, const siginfo_t&) {
325 LOG(ERROR) << "Subprocess " << pid << " exited unexpectedly -"
326 << " attempting to restart";
327
328 HelperProcess* proc;
329 if (pid == adb_proxy_->pid()) {
330 proc = adb_proxy_.get();
331 } else if (pid == mcast_proxy_->pid()) {
332 proc = mcast_proxy_.get();
333 } else if (pid == nd_proxy_->pid()) {
334 proc = nd_proxy_.get();
335 } else {
336 LOG(DFATAL) << "Unknown child process";
337 return;
338 }
339
340 process_reaper_.ForgetChild(pid);
341
hschamf9546312020-04-14 15:12:40 +0900342 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Garrick Evans4c042572019-12-17 13:42:25 +0900343 FROM_HERE,
344 base::Bind(&Manager::RestartSubprocess, weak_factory_.GetWeakPtr(), proc),
345 base::TimeDelta::FromMilliseconds((2 << proc->restarts()) *
346 kSubprocessRestartDelayMs));
347}
348
349void Manager::RestartSubprocess(HelperProcess* subproc) {
350 if (subproc->Restart()) {
351 DCHECK(process_reaper_.WatchForChild(
352 FROM_HERE, subproc->pid(),
353 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
354 subproc->pid())))
355 << "Failed to watch child process " << subproc->pid();
356 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800357}
358
Garrick Evanse94a14e2019-11-11 10:32:13 +0900359bool Manager::StartArc(pid_t pid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900360 if (!arc_svc_->Start(pid))
361 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900362
363 GuestMessage msg;
364 msg.set_event(GuestMessage::START);
365 msg.set_type(GuestMessage::ARC);
366 msg.set_arc_pid(pid);
367 SendGuestMessage(msg);
368
369 return true;
370}
371
Garrick Evans21173b12019-11-20 15:23:16 +0900372void Manager::StopArc(pid_t pid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900373 GuestMessage msg;
374 msg.set_event(GuestMessage::STOP);
375 msg.set_type(GuestMessage::ARC);
376 SendGuestMessage(msg);
377
Garrick Evans21173b12019-11-20 15:23:16 +0900378 arc_svc_->Stop(pid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900379}
380
Garrick Evans015b0d62020-02-07 09:06:38 +0900381bool Manager::StartArcVm(uint32_t cid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900382 if (!arc_svc_->Start(cid))
383 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900384
385 GuestMessage msg;
386 msg.set_event(GuestMessage::START);
387 msg.set_type(GuestMessage::ARC_VM);
388 msg.set_arcvm_vsock_cid(cid);
389 SendGuestMessage(msg);
390
391 return true;
392}
393
Garrick Evans015b0d62020-02-07 09:06:38 +0900394void Manager::StopArcVm(uint32_t cid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900395 GuestMessage msg;
396 msg.set_event(GuestMessage::STOP);
397 msg.set_type(GuestMessage::ARC_VM);
398 SendGuestMessage(msg);
399
Garrick Evans21173b12019-11-20 15:23:16 +0900400 arc_svc_->Stop(cid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900401}
402
Garrick Evans51d5b552020-01-30 10:42:06 +0900403bool Manager::StartCrosVm(uint64_t vm_id,
404 GuestMessage::GuestType vm_type,
Garrick Evans53a2a982020-02-05 10:53:35 +0900405 uint32_t subnet_index) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900406 DCHECK(vm_type == GuestMessage::TERMINA_VM ||
407 vm_type == GuestMessage::PLUGIN_VM);
408
409 if (!cros_svc_->Start(vm_id, vm_type == GuestMessage::TERMINA_VM,
410 subnet_index))
Garrick Evans47c19272019-11-21 10:58:21 +0900411 return false;
412
413 GuestMessage msg;
414 msg.set_event(GuestMessage::START);
Garrick Evans51d5b552020-01-30 10:42:06 +0900415 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900416 SendGuestMessage(msg);
417
418 return true;
419}
420
Garrick Evans51d5b552020-01-30 10:42:06 +0900421void Manager::StopCrosVm(uint64_t vm_id, GuestMessage::GuestType vm_type) {
Garrick Evans47c19272019-11-21 10:58:21 +0900422 GuestMessage msg;
423 msg.set_event(GuestMessage::STOP);
Garrick Evans51d5b552020-01-30 10:42:06 +0900424 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900425 SendGuestMessage(msg);
426
Garrick Evans51d5b552020-01-30 10:42:06 +0900427 cros_svc_->Stop(vm_id, vm_type == GuestMessage::TERMINA_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900428}
429
Garrick Evans08843932019-09-17 14:41:08 +0900430std::unique_ptr<dbus::Response> Manager::OnArcStartup(
431 dbus::MethodCall* method_call) {
432 LOG(INFO) << "ARC++ starting up";
433
434 std::unique_ptr<dbus::Response> dbus_response(
435 dbus::Response::FromMethodCall(method_call));
436
437 dbus::MessageReader reader(method_call);
438 dbus::MessageWriter writer(dbus_response.get());
439
440 patchpanel::ArcStartupRequest request;
441 patchpanel::ArcStartupResponse response;
442
443 if (!reader.PopArrayOfBytesAsProto(&request)) {
444 LOG(ERROR) << "Unable to parse request";
445 writer.AppendProtoAsArrayOfBytes(response);
446 return dbus_response;
447 }
448
Garrick Evanse01bf072019-11-15 09:08:19 +0900449 if (!StartArc(request.pid()))
450 LOG(ERROR) << "Failed to start ARC++ network service";
Garrick Evanse94a14e2019-11-11 10:32:13 +0900451
Garrick Evans08843932019-09-17 14:41:08 +0900452 writer.AppendProtoAsArrayOfBytes(response);
453 return dbus_response;
454}
455
456std::unique_ptr<dbus::Response> Manager::OnArcShutdown(
457 dbus::MethodCall* method_call) {
458 LOG(INFO) << "ARC++ shutting down";
459
460 std::unique_ptr<dbus::Response> dbus_response(
461 dbus::Response::FromMethodCall(method_call));
462
463 dbus::MessageReader reader(method_call);
464 dbus::MessageWriter writer(dbus_response.get());
465
466 patchpanel::ArcShutdownRequest request;
467 patchpanel::ArcShutdownResponse response;
468
469 if (!reader.PopArrayOfBytesAsProto(&request)) {
470 LOG(ERROR) << "Unable to parse request";
471 writer.AppendProtoAsArrayOfBytes(response);
472 return dbus_response;
473 }
474
Garrick Evans21173b12019-11-20 15:23:16 +0900475 StopArc(request.pid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900476
Garrick Evans08843932019-09-17 14:41:08 +0900477 writer.AppendProtoAsArrayOfBytes(response);
478 return dbus_response;
479}
480
481std::unique_ptr<dbus::Response> Manager::OnArcVmStartup(
482 dbus::MethodCall* method_call) {
483 LOG(INFO) << "ARCVM starting up";
484
485 std::unique_ptr<dbus::Response> dbus_response(
486 dbus::Response::FromMethodCall(method_call));
487
488 dbus::MessageReader reader(method_call);
489 dbus::MessageWriter writer(dbus_response.get());
490
491 patchpanel::ArcVmStartupRequest request;
492 patchpanel::ArcVmStartupResponse response;
493
494 if (!reader.PopArrayOfBytesAsProto(&request)) {
495 LOG(ERROR) << "Unable to parse request";
496 writer.AppendProtoAsArrayOfBytes(response);
497 return dbus_response;
498 }
499
Garrick Evans47c19272019-11-21 10:58:21 +0900500 if (!StartArcVm(request.cid())) {
Garrick Evanse01bf072019-11-15 09:08:19 +0900501 LOG(ERROR) << "Failed to start ARCVM network service";
Garrick Evans47c19272019-11-21 10:58:21 +0900502 writer.AppendProtoAsArrayOfBytes(response);
503 return dbus_response;
Garrick Evanse01bf072019-11-15 09:08:19 +0900504 }
Garrick Evanse94a14e2019-11-11 10:32:13 +0900505
Garrick Evans47c19272019-11-21 10:58:21 +0900506 // Populate the response with the known devices.
Garrick Evans38b25a42020-04-06 15:17:42 +0900507 for (const auto* config : arc_svc_->GetDeviceConfigs()) {
508 if (config->tap_ifname().empty())
509 continue;
Garrick Evans47c19272019-11-21 10:58:21 +0900510
Garrick Evans38b25a42020-04-06 15:17:42 +0900511 auto* dev = response.add_devices();
512 dev->set_ifname(config->tap_ifname());
513 dev->set_ipv4_addr(config->guest_ipv4_addr());
514 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900515
Garrick Evans08843932019-09-17 14:41:08 +0900516 writer.AppendProtoAsArrayOfBytes(response);
517 return dbus_response;
518}
519
520std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
521 dbus::MethodCall* method_call) {
522 LOG(INFO) << "ARCVM shutting down";
523
524 std::unique_ptr<dbus::Response> dbus_response(
525 dbus::Response::FromMethodCall(method_call));
526
527 dbus::MessageReader reader(method_call);
528 dbus::MessageWriter writer(dbus_response.get());
529
530 patchpanel::ArcVmShutdownRequest request;
531 patchpanel::ArcVmShutdownResponse response;
532
533 if (!reader.PopArrayOfBytesAsProto(&request)) {
534 LOG(ERROR) << "Unable to parse request";
535 writer.AppendProtoAsArrayOfBytes(response);
536 return dbus_response;
537 }
538
Garrick Evans21173b12019-11-20 15:23:16 +0900539 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900540
Garrick Evans08843932019-09-17 14:41:08 +0900541 writer.AppendProtoAsArrayOfBytes(response);
542 return dbus_response;
543}
544
Garrick Evans47c19272019-11-21 10:58:21 +0900545std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
546 dbus::MethodCall* method_call) {
547 LOG(INFO) << "Termina VM starting up";
548
549 std::unique_ptr<dbus::Response> dbus_response(
550 dbus::Response::FromMethodCall(method_call));
551
552 dbus::MessageReader reader(method_call);
553 dbus::MessageWriter writer(dbus_response.get());
554
555 patchpanel::TerminaVmStartupRequest request;
556 patchpanel::TerminaVmStartupResponse response;
557
558 if (!reader.PopArrayOfBytesAsProto(&request)) {
559 LOG(ERROR) << "Unable to parse request";
560 writer.AppendProtoAsArrayOfBytes(response);
561 return dbus_response;
562 }
563
564 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900565 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900566 LOG(ERROR) << "Failed to start Termina VM network service";
567 writer.AppendProtoAsArrayOfBytes(response);
568 return dbus_response;
569 }
570
Garrick Evans51d5b552020-01-30 10:42:06 +0900571 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900572 if (!tap) {
573 LOG(DFATAL) << "TAP device missing";
574 writer.AppendProtoAsArrayOfBytes(response);
575 return dbus_response;
576 }
Garrick Evans47c19272019-11-21 10:58:21 +0900577
Garrick Evansb1c93712020-01-22 09:28:25 +0900578 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900579 dev->set_ifname(tap->host_ifname());
580 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900581 if (!subnet) {
582 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
583 writer.AppendProtoAsArrayOfBytes(response);
584 return dbus_response;
585 }
586 auto* resp_subnet = dev->mutable_ipv4_subnet();
587 resp_subnet->set_base_addr(subnet->BaseAddress());
588 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900589 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900590 if (!subnet) {
591 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
592 writer.AppendProtoAsArrayOfBytes(response);
593 return dbus_response;
594 }
595 resp_subnet = response.mutable_container_subnet();
596 resp_subnet->set_base_addr(subnet->BaseAddress());
597 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900598
599 writer.AppendProtoAsArrayOfBytes(response);
600 return dbus_response;
601}
602
603std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
604 dbus::MethodCall* method_call) {
605 LOG(INFO) << "Termina VM shutting down";
606
607 std::unique_ptr<dbus::Response> dbus_response(
608 dbus::Response::FromMethodCall(method_call));
609
610 dbus::MessageReader reader(method_call);
611 dbus::MessageWriter writer(dbus_response.get());
612
613 patchpanel::TerminaVmShutdownRequest request;
614 patchpanel::TerminaVmShutdownResponse response;
615
616 if (!reader.PopArrayOfBytesAsProto(&request)) {
617 LOG(ERROR) << "Unable to parse request";
618 writer.AppendProtoAsArrayOfBytes(response);
619 return dbus_response;
620 }
621
Garrick Evans51d5b552020-01-30 10:42:06 +0900622 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
623
624 writer.AppendProtoAsArrayOfBytes(response);
625 return dbus_response;
626}
627
628std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
629 dbus::MethodCall* method_call) {
630 LOG(INFO) << "Plugin VM starting up";
631
632 std::unique_ptr<dbus::Response> dbus_response(
633 dbus::Response::FromMethodCall(method_call));
634
635 dbus::MessageReader reader(method_call);
636 dbus::MessageWriter writer(dbus_response.get());
637
638 patchpanel::PluginVmStartupRequest request;
639 patchpanel::PluginVmStartupResponse response;
640
641 if (!reader.PopArrayOfBytesAsProto(&request)) {
642 LOG(ERROR) << "Unable to parse request";
643 writer.AppendProtoAsArrayOfBytes(response);
644 return dbus_response;
645 }
646
Garrick Evans08fb34b2020-02-20 10:50:17 +0900647 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900648 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900649 LOG(ERROR) << "Failed to start Plugin VM network service";
650 writer.AppendProtoAsArrayOfBytes(response);
651 return dbus_response;
652 }
653
654 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
655 if (!tap) {
656 LOG(DFATAL) << "TAP device missing";
657 writer.AppendProtoAsArrayOfBytes(response);
658 return dbus_response;
659 }
660
Garrick Evans51d5b552020-01-30 10:42:06 +0900661 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900662 dev->set_ifname(tap->host_ifname());
663 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900664 if (!subnet) {
665 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
666 writer.AppendProtoAsArrayOfBytes(response);
667 return dbus_response;
668 }
669 auto* resp_subnet = dev->mutable_ipv4_subnet();
670 resp_subnet->set_base_addr(subnet->BaseAddress());
671 resp_subnet->set_prefix_len(subnet->PrefixLength());
672
673 writer.AppendProtoAsArrayOfBytes(response);
674 return dbus_response;
675}
676
677std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
678 dbus::MethodCall* method_call) {
679 LOG(INFO) << "Plugin VM shutting down";
680
681 std::unique_ptr<dbus::Response> dbus_response(
682 dbus::Response::FromMethodCall(method_call));
683
684 dbus::MessageReader reader(method_call);
685 dbus::MessageWriter writer(dbus_response.get());
686
687 patchpanel::PluginVmShutdownRequest request;
688 patchpanel::PluginVmShutdownResponse response;
689
690 if (!reader.PopArrayOfBytesAsProto(&request)) {
691 LOG(ERROR) << "Unable to parse request";
692 writer.AppendProtoAsArrayOfBytes(response);
693 return dbus_response;
694 }
695
696 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900697
698 writer.AppendProtoAsArrayOfBytes(response);
699 return dbus_response;
700}
701
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900702std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
703 dbus::MethodCall* method_call) {
704 std::unique_ptr<dbus::Response> dbus_response(
705 dbus::Response::FromMethodCall(method_call));
706
707 dbus::MessageReader reader(method_call);
708 dbus::MessageWriter writer(dbus_response.get());
709
710 patchpanel::SetVpnIntentRequest request;
711 patchpanel::SetVpnIntentResponse response;
712
713 bool success = reader.PopArrayOfBytesAsProto(&request);
714 if (!success) {
715 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
716 // Do not return yet to make sure we close the received fd.
717 }
718
719 base::ScopedFD client_socket;
720 reader.PopFileDescriptor(&client_socket);
721
722 if (success)
723 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
724
725 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900726
727 writer.AppendProtoAsArrayOfBytes(response);
728 return dbus_response;
729}
730
731std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
732 dbus::MethodCall* method_call) {
733 std::unique_ptr<dbus::Response> dbus_response(
734 dbus::Response::FromMethodCall(method_call));
735
736 dbus::MessageReader reader(method_call);
737 dbus::MessageWriter writer(dbus_response.get());
738
739 patchpanel::ConnectNamespaceRequest request;
740 patchpanel::ConnectNamespaceResponse response;
741
Hugo Benichicc6850f2020-01-17 13:26:06 +0900742 bool success = true;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900743 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900744 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
745 // Do not return yet to make sure we close the received fd and
746 // validate other arguments.
747 success = false;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900748 }
749
Hugo Benichicc6850f2020-01-17 13:26:06 +0900750 base::ScopedFD client_fd;
751 reader.PopFileDescriptor(&client_fd);
752 if (!client_fd.is_valid()) {
753 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
754 success = false;
755 }
756
757 pid_t pid = request.pid();
758 {
759 ScopedNS ns(pid);
760 if (!ns.IsValid()) {
761 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
762 success = false;
763 }
764 }
765
766 const std::string& outbound_ifname = request.outbound_physical_device();
767 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
768 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
769 << outbound_ifname;
770 success = false;
771 }
772
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900773 if (success)
774 ConnectNamespace(std::move(client_fd), request, response);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900775
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900776 writer.AppendProtoAsArrayOfBytes(response);
777 return dbus_response;
778}
779
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900780void Manager::ConnectNamespace(
781 base::ScopedFD client_fd,
782 const patchpanel::ConnectNamespaceRequest& request,
783 patchpanel::ConnectNamespaceResponse& response) {
784 std::unique_ptr<Subnet> subnet =
785 addr_mgr_.AllocateIPv4Subnet(AddressManager::Guest::MINIJAIL_NETNS);
786 if (!subnet) {
787 LOG(ERROR) << "ConnectNamespaceRequest: exhausted IPv4 subnet space";
788 return;
789 }
790
791 const std::string ifname_id = std::to_string(connected_namespaces_next_id_);
792 const std::string host_ifname = "arc_ns" + ifname_id;
793 const std::string client_ifname = "veth" + ifname_id;
Hugo Benichie8758b52020-04-03 14:49:01 +0900794 const uint32_t host_ipv4_addr = subnet->AddressAtOffset(0);
795 const uint32_t client_ipv4_addr = subnet->AddressAtOffset(1);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900796
Hugo Benichie8758b52020-04-03 14:49:01 +0900797 // Veth interface configuration and client routing configuration:
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900798 // - create veth pair inside client namespace.
799 // - configure IPv4 address on remote veth inside client namespace.
Hugo Benichie8758b52020-04-03 14:49:01 +0900800 // - configure IPv4 address on local veth inside host namespace.
801 // - add a default IPv4 /0 route sending traffic to that remote veth.
802 // - bring back one veth to the host namespace, and set it up.
803 pid_t pid = request.pid();
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900804 if (!datapath_->ConnectVethPair(pid, host_ifname, client_ifname,
805 addr_mgr_.GenerateMacAddress(),
806 client_ipv4_addr, subnet->PrefixLength(),
807 false /* enable_multicast */)) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900808 LOG(ERROR) << "ConnectNamespaceRequest: failed to create veth pair for "
809 "namespace pid "
810 << pid;
811 return;
812 }
813 if (!datapath_->ConfigureInterface(
814 host_ifname, addr_mgr_.GenerateMacAddress(), host_ipv4_addr,
815 subnet->PrefixLength(), true /* link up */,
816 false /* enable_multicast */)) {
817 LOG(ERROR) << "ConnectNamespaceRequest: cannot configure host interface "
818 << host_ifname;
819 datapath_->RemoveInterface(host_ifname);
820 return;
821 }
822 {
823 ScopedNS ns(pid);
824 if (!ns.IsValid()) {
825 LOG(ERROR) << "ConnectNamespaceRequest: cannot enter client pid " << pid;
826 datapath_->RemoveInterface(host_ifname);
827 return;
828 }
829 if (!datapath_->AddIPv4Route(host_ipv4_addr, INADDR_ANY, INADDR_ANY)) {
830 LOG(ERROR)
831 << "ConnectNamespaceRequest: failed to add default /0 route to "
832 << host_ifname << " inside namespace pid " << pid;
833 datapath_->RemoveInterface(host_ifname);
834 return;
835 }
836 }
837
838 // Host namespace routing configuration
839 // - ingress: add route to client subnet via |host_ifname|.
840 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
841 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
842 // Note that by default unsolicited ingress traffic is not forwarded to the
843 // client namespace unless the client specifically set port forwarding
844 // through permission_broker DBus APIs.
845 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
846 // both ways between client namespace and other guest containers and VMs.
847 // TODO(hugobenichi) If outbound_physical_device is defined, then set strong
848 // routing to that interface routing table.
849 if (!datapath_->AddIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
850 subnet->Netmask())) {
851 LOG(ERROR)
852 << "ConnectNamespaceRequest: failed to set route to client namespace";
853 datapath_->RemoveInterface(host_ifname);
854 return;
855 }
856 if (!datapath_->AddOutboundIPv4(host_ifname)) {
857 LOG(ERROR) << "ConnectNamespaceRequest: failed to allow FORWARD for "
858 "traffic outgoing from "
859 << host_ifname;
860 datapath_->RemoveInterface(host_ifname);
861 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
862 subnet->Netmask());
863 return;
864 }
865 if (!datapath_->AddOutboundIPv4SNATMark(host_ifname)) {
866 LOG(ERROR) << "ConnectNamespaceRequest: failed to set SNAT for traffic "
867 "outgoing from "
868 << host_ifname;
869 datapath_->RemoveInterface(host_ifname);
870 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
871 subnet->Netmask());
872 datapath_->RemoveOutboundIPv4(host_ifname);
873 return;
874 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900875
Hugo Benichi7352ad92020-04-07 16:11:59 +0900876 // Dup the client fd into our own: this guarantees that the fd number will
877 // be stable and tied to the actual kernel resources used by the client.
878 base::ScopedFD local_client_fd(dup(client_fd.get()));
879 if (!local_client_fd.is_valid()) {
880 PLOG(ERROR) << "ConnectNamespaceRequest: failed to dup() client fd";
Hugo Benichie8758b52020-04-03 14:49:01 +0900881 datapath_->RemoveInterface(host_ifname);
882 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
883 subnet->Netmask());
884 datapath_->RemoveOutboundIPv4(host_ifname);
885 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900886 return;
887 }
888
889 // Add the dupe fd to the epoll watcher.
890 // TODO(hugobenichi) Find a way to reuse base::FileDescriptorWatcher for
891 // listening to EPOLLHUP.
892 struct epoll_event epevent;
893 epevent.events = EPOLLIN; // EPOLLERR | EPOLLHUP are always waited for.
894 epevent.data.fd = local_client_fd.get();
895 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_ADD,
896 local_client_fd.get(), &epevent) != 0) {
897 PLOG(ERROR) << "ConnectNamespaceResponse: epoll_ctl(EPOLL_CTL_ADD) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900898 datapath_->RemoveInterface(host_ifname);
899 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
900 subnet->Netmask());
901 datapath_->RemoveOutboundIPv4(host_ifname);
902 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900903 return;
904 }
905
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900906 // Prepare the response before storing ConnectNamespaceInfo.
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900907 response.set_peer_ifname(client_ifname);
908 response.set_peer_ipv4_address(host_ipv4_addr);
909 response.set_host_ifname(host_ifname);
910 response.set_host_ipv4_address(client_ipv4_addr);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900911 auto* response_subnet = response.mutable_ipv4_subnet();
912 response_subnet->set_base_addr(subnet->BaseAddress());
913 response_subnet->set_prefix_len(subnet->PrefixLength());
914
915 // Store ConnectNamespaceInfo
916 connected_namespaces_next_id_++;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900917 int fdkey = local_client_fd.release();
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900918 connected_namespaces_[fdkey] = {};
919 ConnectNamespaceInfo& ns_info = connected_namespaces_[fdkey];
920 ns_info.pid = request.pid();
921 ns_info.outbound_ifname = request.outbound_physical_device();
922 ns_info.host_ifname = std::move(host_ifname);
923 ns_info.client_ifname = std::move(client_ifname);
924 ns_info.client_subnet = std::move(subnet);
925
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900926 LOG(INFO) << "Connected network namespace " << ns_info;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900927
928 if (connected_namespaces_.size() == 1) {
929 LOG(INFO) << "Starting ConnectNamespace client fds monitoring";
930 CheckConnectedNamespaces();
931 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900932}
933
934void Manager::DisconnectNamespace(int client_fd) {
935 auto it = connected_namespaces_.find(client_fd);
936 if (it == connected_namespaces_.end()) {
937 LOG(ERROR) << "No ConnectNamespaceInfo found for client_fd " << client_fd;
938 return;
939 }
940
Hugo Benichi7352ad92020-04-07 16:11:59 +0900941 // Remove the client fd dupe from the epoll watcher and close it.
942 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL, client_fd,
Hugo Benichie8758b52020-04-03 14:49:01 +0900943 nullptr) != 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900944 PLOG(ERROR) << "DisconnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900945 if (close(client_fd) < 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900946 PLOG(ERROR) << "DisconnectNamespace: close(client_fd) failed";
Hugo Benichi7352ad92020-04-07 16:11:59 +0900947
Hugo Benichie8758b52020-04-03 14:49:01 +0900948 // Destroy the interface configuration and routing configuration:
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900949 // - destroy veth pair.
Hugo Benichie8758b52020-04-03 14:49:01 +0900950 // - remove forwarding rules on host namespace.
951 // - remove SNAT marking rule on host namespace.
952 // Note that the default route set inside the client namespace by patchpanel
953 // is not destroyed: it is assumed the client will also teardown its
954 // namespace if it triggered DisconnectNamespace.
955 datapath_->RemoveInterface(it->second.host_ifname);
956 datapath_->RemoveOutboundIPv4(it->second.host_ifname);
957 datapath_->RemoveOutboundIPv4SNATMark(it->second.host_ifname);
958 datapath_->DeleteIPv4Route(it->second.client_subnet->AddressAtOffset(0),
959 it->second.client_subnet->BaseAddress(),
960 it->second.client_subnet->Netmask());
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900961
962 LOG(INFO) << "Disconnected network namespace " << it->second;
963
964 // This release the allocated IPv4 subnet.
965 connected_namespaces_.erase(it);
966}
967
Hugo Benichi7352ad92020-04-07 16:11:59 +0900968// TODO(hugobenichi) Generalize this check to all resources created by
969// patchpanel on behalf of a remote client.
970void Manager::CheckConnectedNamespaces() {
971 int max_event = 10;
972 struct epoll_event epevents[max_event];
973 int nready = epoll_wait(connected_namespaces_epollfd_, epevents, max_event,
974 0 /* do not block */);
975 if (nready < 0)
976 PLOG(ERROR) << "CheckConnectedNamespaces: epoll_wait(0) failed";
977
978 for (int i = 0; i < nready; i++)
979 if (epevents[i].events & (EPOLLHUP | EPOLLERR))
980 DisconnectNamespace(epevents[i].data.fd);
981
982 if (connected_namespaces_.empty()) {
983 LOG(INFO) << "Stopping ConnectNamespace client fds monitoring";
984 return;
985 }
986
Qijiang Fan2d7aeb42020-05-19 02:06:39 +0900987 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Hugo Benichi7352ad92020-04-07 16:11:59 +0900988 FROM_HERE,
989 base::Bind(&Manager::CheckConnectedNamespaces,
Hugo Benichie8758b52020-04-03 14:49:01 +0900990 weak_factory_.GetWeakPtr()),
Hugo Benichi7352ad92020-04-07 16:11:59 +0900991 kConnectNamespaceCheckInterval);
992}
993
Garrick Evanse94a14e2019-11-11 10:32:13 +0900994void Manager::SendGuestMessage(const GuestMessage& msg) {
Garrick Evans96e03042019-05-28 14:30:52 +0900995 IpHelperMessage ipm;
996 *ipm.mutable_guest_message() = msg;
Garrick Evans96e03042019-05-28 14:30:52 +0900997 adb_proxy_->SendMessage(ipm);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900998 mcast_proxy_->SendMessage(ipm);
999 nd_proxy_->SendMessage(ipm);
Garrick Evans96e03042019-05-28 14:30:52 +09001000}
1001
Garrick Evans4ac09852020-01-16 14:09:22 +09001002void Manager::StartForwarding(const std::string& ifname_physical,
1003 const std::string& ifname_virtual,
Garrick Evans4ac09852020-01-16 14:09:22 +09001004 bool ipv6,
1005 bool multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001006 if (ifname_physical.empty() || ifname_virtual.empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001007 return;
1008
1009 IpHelperMessage ipm;
1010 DeviceMessage* msg = ipm.mutable_device_message();
1011 msg->set_dev_ifname(ifname_physical);
Garrick Evans4ac09852020-01-16 14:09:22 +09001012 msg->set_br_ifname(ifname_virtual);
1013
1014 if (ipv6) {
1015 LOG(INFO) << "Starting IPv6 forwarding from " << ifname_physical << " to "
1016 << ifname_virtual;
1017
1018 if (!datapath_->AddIPv6Forwarding(ifname_physical, ifname_virtual)) {
1019 LOG(ERROR) << "Failed to setup iptables forwarding rule for IPv6 from "
1020 << ifname_physical << " to " << ifname_virtual;
1021 }
1022 if (!datapath_->MaskInterfaceFlags(ifname_physical, IFF_ALLMULTI)) {
1023 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1024 << ifname_physical;
1025 }
1026 if (!datapath_->MaskInterfaceFlags(ifname_virtual, IFF_ALLMULTI)) {
1027 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1028 << ifname_virtual;
1029 }
1030 nd_proxy_->SendMessage(ipm);
1031 }
1032
1033 if (multicast) {
1034 LOG(INFO) << "Starting multicast forwarding from " << ifname_physical
1035 << " to " << ifname_virtual;
1036 mcast_proxy_->SendMessage(ipm);
1037 }
1038}
1039
1040void Manager::StopForwarding(const std::string& ifname_physical,
1041 const std::string& ifname_virtual,
1042 bool ipv6,
1043 bool multicast) {
1044 if (ifname_physical.empty())
1045 return;
1046
1047 IpHelperMessage ipm;
1048 DeviceMessage* msg = ipm.mutable_device_message();
1049 msg->set_dev_ifname(ifname_physical);
1050 msg->set_teardown(true);
Taoyu Li7dca19a2020-03-16 16:27:07 +09001051 if (!ifname_virtual.empty()) {
1052 msg->set_br_ifname(ifname_virtual);
1053 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001054
1055 if (ipv6) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001056 if (ifname_virtual.empty()) {
1057 LOG(INFO) << "Stopping IPv6 forwarding on " << ifname_physical;
1058 } else {
1059 LOG(INFO) << "Stopping IPv6 forwarding from " << ifname_physical << " to "
1060 << ifname_virtual;
1061 datapath_->RemoveIPv6Forwarding(ifname_physical, ifname_virtual);
1062 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001063 nd_proxy_->SendMessage(ipm);
1064 }
1065
1066 if (multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001067 if (ifname_virtual.empty()) {
1068 LOG(INFO) << "Stopping multicast forwarding on " << ifname_physical;
1069 } else {
1070 LOG(INFO) << "Stopping multicast forwarding from " << ifname_physical
1071 << " to " << ifname_virtual;
1072 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001073 mcast_proxy_->SendMessage(ipm);
1074 }
1075}
1076
Garrick Evans4ac09852020-01-16 14:09:22 +09001077void Manager::OnDeviceMessageFromNDProxy(const DeviceMessage& msg) {
1078 LOG_IF(DFATAL, msg.dev_ifname().empty())
1079 << "Received DeviceMessage w/ empty dev_ifname";
1080
1081 if (!datapath_->AddIPv6HostRoute(msg.dev_ifname(), msg.guest_ip6addr(),
1082 128)) {
1083 LOG(WARNING) << "Failed to setup the IPv6 route for interface "
1084 << msg.dev_ifname();
1085 }
1086}
1087
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001088std::ostream& operator<<(std::ostream& stream,
1089 const Manager::ConnectNamespaceInfo& ns_info) {
1090 stream << "{ pid: " << ns_info.pid;
1091 if (!ns_info.outbound_ifname.empty()) {
1092 stream << ", outbound_ifname: " << ns_info.outbound_ifname;
1093 }
1094 stream << ", host_ifname: " << ns_info.host_ifname
1095 << ", client_ifname: " << ns_info.client_ifname
1096 << ", subnet: " << ns_info.client_subnet->ToCidrString() << '}';
1097 return stream;
1098}
1099
Garrick Evans3388a032020-03-24 11:25:55 +09001100} // namespace patchpanel