blob: c279c3e39273f646b91bb61843b87af7e7d36d23 [file] [log] [blame]
Kevin Cernekee95d4ae92016-06-19 10:26:29 -07001// Copyright 2016 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Garrick Evans3388a032020-03-24 11:25:55 +09005#include "patchpanel/manager.h"
Kevin Cernekee4e62cc12016-12-03 11:50:53 -08006
Kevin Cernekee95d4ae92016-06-19 10:26:29 -07007#include <arpa/inet.h>
Garrick Evans4ac09852020-01-16 14:09:22 +09008#include <net/if.h>
Hugo Benichi935eca92018-07-03 13:47:24 +09009#include <netinet/in.h>
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070010#include <stdint.h>
Hugo Benichi7352ad92020-04-07 16:11:59 +090011#include <sys/epoll.h>
Garrick Evans54861622019-07-19 09:05:09 +090012#include <sys/prctl.h>
Garrick Evans96e03042019-05-28 14:30:52 +090013#include <sys/socket.h>
14#include <sys/un.h>
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070015
Kevin Cernekee27bcaa62016-12-03 11:16:26 -080016#include <utility>
17
Hugo Benichi7d9d8db2020-03-30 15:56:56 +090018#include "base/files/scoped_file.h"
Hugo Benichicc6850f2020-01-17 13:26:06 +090019#include <base/bind.h>
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070020#include <base/logging.h>
Taoyu Lic85c44b2019-12-04 17:32:57 +090021#include <base/strings/string_number_conversions.h>
Garrick Evans96e03042019-05-28 14:30:52 +090022#include <base/strings/string_split.h>
Garrick Evans6f258d02019-06-28 16:32:07 +090023#include <base/strings/string_util.h>
Taoyu Li179dcc62019-10-17 11:21:08 +090024#include <base/strings/stringprintf.h>
hschamf9546312020-04-14 15:12:40 +090025#include <base/threading/thread_task_runner_handle.h>
Taoyu Lic85c44b2019-12-04 17:32:57 +090026#include <brillo/key_value_store.h>
Kevin Cernekee27bcaa62016-12-03 11:16:26 -080027#include <brillo/minijail/minijail.h>
28
Garrick Evans3388a032020-03-24 11:25:55 +090029#include "patchpanel/ipc.pb.h"
30#include "patchpanel/mac_address_generator.h"
31#include "patchpanel/net_util.h"
32#include "patchpanel/routing_service.h"
33#include "patchpanel/scoped_ns.h"
Garrick Evans428e4762018-12-11 15:18:42 +090034
Garrick Evans3388a032020-03-24 11:25:55 +090035namespace patchpanel {
Garrick Evans08843932019-09-17 14:41:08 +090036namespace {
Garrick Evans4c042572019-12-17 13:42:25 +090037constexpr int kSubprocessRestartDelayMs = 900;
Garrick Evans08843932019-09-17 14:41:08 +090038
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +090039constexpr char kNDProxyFeatureName[] = "ARC NDProxy";
40constexpr int kNDProxyMinAndroidSdkVersion = 28; // P
41constexpr int kNDProxyMinChromeMilestone = 80;
Taoyu Lic85c44b2019-12-04 17:32:57 +090042
Hugo Benichi7352ad92020-04-07 16:11:59 +090043// Time interval between epoll checks on file descriptors committed by callers
44// of ConnectNamespace DBus API.
45constexpr const base::TimeDelta kConnectNamespaceCheckInterval =
Hugo Benichifa9462e2020-06-26 09:50:48 +090046 base::TimeDelta::FromSeconds(5);
Hugo Benichi7352ad92020-04-07 16:11:59 +090047
Garrick Evans08843932019-09-17 14:41:08 +090048// Passes |method_call| to |handler| and passes the response to
49// |response_sender|. If |handler| returns nullptr, an empty response is
50// created and sent.
51void HandleSynchronousDBusMethodCall(
52 base::Callback<std::unique_ptr<dbus::Response>(dbus::MethodCall*)> handler,
53 dbus::MethodCall* method_call,
54 dbus::ExportedObject::ResponseSender response_sender) {
55 std::unique_ptr<dbus::Response> response = handler.Run(method_call);
56 if (!response)
57 response = dbus::Response::FromMethodCall(method_call);
58 response_sender.Run(std::move(response));
59}
60
61} // namespace
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070062
Taoyu Lice7caa62019-10-01 15:43:33 +090063Manager::Manager(std::unique_ptr<HelperProcess> adb_proxy,
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090064 std::unique_ptr<HelperProcess> mcast_proxy,
Garrick Evans1f5a3612019-11-08 12:59:03 +090065 std::unique_ptr<HelperProcess> nd_proxy)
Garrick Evans3915af32019-07-25 15:44:34 +090066 : adb_proxy_(std::move(adb_proxy)),
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090067 mcast_proxy_(std::move(mcast_proxy)),
Garrick Evans4ee5ce22020-03-18 07:05:17 +090068 nd_proxy_(std::move(nd_proxy)) {
Taoyu Li179dcc62019-10-17 11:21:08 +090069 runner_ = std::make_unique<MinijailedProcessRunner>();
70 datapath_ = std::make_unique<Datapath>(runner_.get());
Hugo Benichi7352ad92020-04-07 16:11:59 +090071 connected_namespaces_epollfd_ = epoll_create(1 /* size */);
Taoyu Li179dcc62019-10-17 11:21:08 +090072}
Long Chengd4415582019-09-24 19:16:09 +000073
Garrick Evans207e7482019-12-16 11:54:36 +090074Manager::~Manager() {
75 OnShutdown(nullptr);
76}
77
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +090078std::map<const std::string, bool> Manager::cached_feature_enabled_ = {};
79
80bool Manager::ShouldEnableFeature(
81 int min_android_sdk_version,
82 int min_chrome_milestone,
83 const std::vector<std::string>& supported_boards,
84 const std::string& feature_name) {
85 static const char kLsbReleasePath[] = "/etc/lsb-release";
86
87 const auto& cached_result = cached_feature_enabled_.find(feature_name);
88 if (cached_result != cached_feature_enabled_.end())
89 return cached_result->second;
90
91 auto check = [min_android_sdk_version, min_chrome_milestone,
92 &supported_boards, &feature_name]() {
93 brillo::KeyValueStore store;
94 if (!store.Load(base::FilePath(kLsbReleasePath))) {
95 LOG(ERROR) << "Could not read lsb-release";
96 return false;
97 }
98
99 std::string value;
100 if (!store.GetString("CHROMEOS_ARC_ANDROID_SDK_VERSION", &value)) {
101 LOG(ERROR) << feature_name
102 << " disabled - cannot determine Android SDK version";
103 return false;
104 }
105 int ver = 0;
106 if (!base::StringToInt(value.c_str(), &ver)) {
107 LOG(ERROR) << feature_name << " disabled - invalid Android SDK version";
108 return false;
109 }
110 if (ver < min_android_sdk_version) {
111 LOG(INFO) << feature_name << " disabled for Android SDK " << value;
112 return false;
113 }
114
115 if (!store.GetString("CHROMEOS_RELEASE_CHROME_MILESTONE", &value)) {
116 LOG(ERROR) << feature_name
117 << " disabled - cannot determine ChromeOS milestone";
118 return false;
119 }
120 if (!base::StringToInt(value.c_str(), &ver)) {
121 LOG(ERROR) << feature_name << " disabled - invalid ChromeOS milestone";
122 return false;
123 }
124 if (ver < min_chrome_milestone) {
125 LOG(INFO) << feature_name << " disabled for ChromeOS milestone " << value;
126 return false;
127 }
128
129 if (!store.GetString("CHROMEOS_RELEASE_BOARD", &value)) {
130 LOG(ERROR) << feature_name << " disabled - cannot determine board";
131 return false;
132 }
133 if (!supported_boards.empty() &&
134 std::find(supported_boards.begin(), supported_boards.end(), value) ==
135 supported_boards.end()) {
136 LOG(INFO) << feature_name << " disabled for board " << value;
137 return false;
138 }
139 return true;
140 };
141
142 bool result = check();
143 cached_feature_enabled_.emplace(feature_name, result);
144 return result;
145}
146
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700147int Manager::OnInit() {
Garrick Evans54861622019-07-19 09:05:09 +0900148 prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800149
150 // Handle subprocess lifecycle.
151 process_reaper_.Register(this);
Hugo Benichi935eca92018-07-03 13:47:24 +0900152
153 CHECK(process_reaper_.WatchForChild(
Garrick Evans96e03042019-05-28 14:30:52 +0900154 FROM_HERE, adb_proxy_->pid(),
155 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
156 adb_proxy_->pid())))
157 << "Failed to watch adb-proxy child process";
Taoyu Liaf944c92019-10-01 12:22:31 +0900158 CHECK(process_reaper_.WatchForChild(
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900159 FROM_HERE, mcast_proxy_->pid(),
160 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
161 nd_proxy_->pid())))
162 << "Failed to watch multicast-proxy child process";
163 CHECK(process_reaper_.WatchForChild(
Taoyu Liaf944c92019-10-01 12:22:31 +0900164 FROM_HERE, nd_proxy_->pid(),
165 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
166 nd_proxy_->pid())))
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900167 << "Failed to watch nd-proxy child process";
Garrick Evans96e03042019-05-28 14:30:52 +0900168
Garrick Evans49879532018-12-03 13:15:36 +0900169 // Run after Daemon::OnInit().
hschamf9546312020-04-14 15:12:40 +0900170 base::ThreadTaskRunnerHandle::Get()->PostTask(
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700171 FROM_HERE,
172 base::Bind(&Manager::InitialSetup, weak_factory_.GetWeakPtr()));
173
174 return DBusDaemon::OnInit();
175}
176
177void Manager::InitialSetup() {
Garrick Evans08843932019-09-17 14:41:08 +0900178 LOG(INFO) << "Setting up DBus service interface";
179 dbus_svc_path_ = bus_->GetExportedObject(
180 dbus::ObjectPath(patchpanel::kPatchPanelServicePath));
181 if (!dbus_svc_path_) {
182 LOG(FATAL) << "Failed to export " << patchpanel::kPatchPanelServicePath
183 << " object";
184 }
185
186 using ServiceMethod =
187 std::unique_ptr<dbus::Response> (Manager::*)(dbus::MethodCall*);
188 const std::map<const char*, ServiceMethod> kServiceMethods = {
189 {patchpanel::kArcStartupMethod, &Manager::OnArcStartup},
190 {patchpanel::kArcShutdownMethod, &Manager::OnArcShutdown},
191 {patchpanel::kArcVmStartupMethod, &Manager::OnArcVmStartup},
192 {patchpanel::kArcVmShutdownMethod, &Manager::OnArcVmShutdown},
Garrick Evans47c19272019-11-21 10:58:21 +0900193 {patchpanel::kTerminaVmStartupMethod, &Manager::OnTerminaVmStartup},
194 {patchpanel::kTerminaVmShutdownMethod, &Manager::OnTerminaVmShutdown},
Garrick Evans51d5b552020-01-30 10:42:06 +0900195 {patchpanel::kPluginVmStartupMethod, &Manager::OnPluginVmStartup},
196 {patchpanel::kPluginVmShutdownMethod, &Manager::OnPluginVmShutdown},
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900197 {patchpanel::kSetVpnIntentMethod, &Manager::OnSetVpnIntent},
Hugo Benichib56b77c2020-01-15 16:00:56 +0900198 {patchpanel::kConnectNamespaceMethod, &Manager::OnConnectNamespace},
Garrick Evans08843932019-09-17 14:41:08 +0900199 };
200
201 for (const auto& kv : kServiceMethods) {
202 if (!dbus_svc_path_->ExportMethodAndBlock(
203 patchpanel::kPatchPanelInterface, kv.first,
204 base::Bind(&HandleSynchronousDBusMethodCall,
205 base::Bind(kv.second, base::Unretained(this))))) {
206 LOG(FATAL) << "Failed to export method " << kv.first;
207 }
208 }
209
210 if (!bus_->RequestOwnershipAndBlock(patchpanel::kPatchPanelServiceName,
211 dbus::Bus::REQUIRE_PRIMARY)) {
212 LOG(FATAL) << "Failed to take ownership of "
213 << patchpanel::kPatchPanelServiceName;
214 }
215 LOG(INFO) << "DBus service interface ready";
216
Taoyu Li6d479442019-12-09 13:02:29 +0900217 auto& runner = datapath_->runner();
Garrick Evans7cf8c542020-05-25 09:50:17 +0900218 // Enable IPv4 packet forwarding
219 if (runner.sysctl_w("net.ipv4.ip_forward", "1") != 0) {
220 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
221 << " Guest connectivity will not work correctly.";
222 }
Garrick Evans28d194e2019-12-17 10:22:28 +0900223 // Limit local port range: Android owns 47104-61000.
224 // TODO(garrick): The original history behind this tweak is gone. Some
225 // investigation is needed to see if it is still applicable.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900226 if (runner.sysctl_w("net.ipv4.ip_local_port_range", "32768 47103") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900227 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
228 << " apps may not work correctly.";
229 }
Taoyu Li6d479442019-12-09 13:02:29 +0900230 // Enable IPv6 packet forarding
Garrick Evans8e8e3472020-01-23 14:03:50 +0900231 if (runner.sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0) {
Taoyu Li6d479442019-12-09 13:02:29 +0900232 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
233 << " IPv6 functionality may be broken.";
234 }
235 // Kernel proxy_ndp is only needed for legacy IPv6 configuration
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +0900236 if (!ShouldEnableFeature(kNDProxyMinAndroidSdkVersion,
Garrick Evansf5862122020-03-16 09:13:45 +0900237 kNDProxyMinChromeMilestone, {},
238 kNDProxyFeatureName) &&
Garrick Evans8e8e3472020-01-23 14:03:50 +0900239 runner.sysctl_w("net.ipv6.conf.all.proxy_ndp", "1") != 0) {
Taoyu Li6d479442019-12-09 13:02:29 +0900240 LOG(ERROR) << "Failed to update net.ipv6.conf.all.proxy_ndp."
241 << " IPv6 functionality may be broken.";
242 }
243
Garrick Evansd291af62020-05-25 10:39:06 +0900244 if (!datapath_->AddSNATMarkRules()) {
245 LOG(ERROR) << "Failed to install SNAT mark rules."
246 << " Guest connectivity may be broken.";
247 }
248 if (!datapath_->AddForwardEstablishedRule()) {
249 LOG(ERROR) << "Failed to install forwarding rule for established"
250 << " connections.";
251 }
252
Garrick Evansff6e37f2020-05-25 10:54:47 +0900253 // TODO(chromium:898210): Move interface-specific masquerading setup to shill;
254 // such that we can better set up the masquerade rules based on connection
255 // type rather than interface names.
256 if (!datapath_->AddInterfaceSNAT("wwan+")) {
257 LOG(ERROR) << "Failed to set up wifi masquerade";
258 }
259
Garrick Evansc50426b2020-05-25 11:00:55 +0900260 if (!datapath_->AddOutboundIPv4SNATMark("vmtap+")) {
261 LOG(ERROR) << "Failed to set up NAT for TAP devices."
262 << " Guest connectivity may be broken.";
263 }
264
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900265 routing_svc_ = std::make_unique<RoutingService>();
266
Garrick Evans4ac09852020-01-16 14:09:22 +0900267 nd_proxy_->RegisterDeviceMessageHandler(base::Bind(
268 &Manager::OnDeviceMessageFromNDProxy, weak_factory_.GetWeakPtr()));
269
Garrick Evans69b85872020-02-04 11:40:26 +0900270 shill_client_ = std::make_unique<ShillClient>(bus_);
Garrick Evans1b1f67c2020-02-04 16:21:25 +0900271 auto* const forwarder = static_cast<TrafficForwarder*>(this);
Garrick Evans5d55f5e2019-07-17 15:28:10 +0900272
Hugo Benichiad1bdd92020-06-12 13:48:37 +0900273 GuestMessage::GuestType arc_guest =
274 USE_ARCVM ? GuestMessage::ARC_VM : GuestMessage::ARC;
275 arc_svc_ = std::make_unique<ArcService>(shill_client_.get(), datapath_.get(),
276 &addr_mgr_, forwarder, arc_guest);
Garrick Evans1b1f67c2020-02-04 16:21:25 +0900277 cros_svc_ = std::make_unique<CrostiniService>(shill_client_.get(), &addr_mgr_,
278 datapath_.get(), forwarder);
Jie Jiang01c1a2e2020-04-08 20:58:30 +0900279 network_monitor_svc_ =
280 std::make_unique<NetworkMonitorService>(shill_client_.get());
281 network_monitor_svc_->Start();
Taoyu Liaf944c92019-10-01 12:22:31 +0900282
283 nd_proxy_->Listen();
Long Chengd4415582019-09-24 19:16:09 +0000284}
Garrick Evans49879532018-12-03 13:15:36 +0900285
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800286void Manager::OnShutdown(int* exit_code) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900287 LOG(INFO) << "Shutting down and cleaning up";
Garrick Evans207e7482019-12-16 11:54:36 +0900288 cros_svc_.reset();
289 arc_svc_.reset();
Hugo Benichi7352ad92020-04-07 16:11:59 +0900290 close(connected_namespaces_epollfd_);
Hugo Benichie8758b52020-04-03 14:49:01 +0900291 // Tear down any remaining connected namespace.
292 std::vector<int> connected_namespaces_fdkeys;
293 for (const auto& kv : connected_namespaces_)
294 connected_namespaces_fdkeys.push_back(kv.first);
295 for (const int fdkey : connected_namespaces_fdkeys)
296 DisconnectNamespace(fdkey);
Garrick Evans28d194e2019-12-17 10:22:28 +0900297
Garrick Evansc50426b2020-05-25 11:00:55 +0900298 datapath_->RemoveOutboundIPv4SNATMark("vmtap+");
Garrick Evansff6e37f2020-05-25 10:54:47 +0900299 datapath_->RemoveInterfaceSNAT("wwan+");
Garrick Evansd291af62020-05-25 10:39:06 +0900300 datapath_->RemoveForwardEstablishedRule();
301 datapath_->RemoveSNATMarkRules();
302
Garrick Evans7cf8c542020-05-25 09:50:17 +0900303 auto& runner = datapath_->runner();
Garrick Evans28d194e2019-12-17 10:22:28 +0900304 // Restore original local port range.
305 // TODO(garrick): The original history behind this tweak is gone. Some
306 // investigation is needed to see if it is still applicable.
Garrick Evans7cf8c542020-05-25 09:50:17 +0900307 if (runner.sysctl_w("net.ipv4.ip_local_port_range", "32768 61000") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900308 LOG(ERROR) << "Failed to restore local port range";
309 }
Garrick Evans7cf8c542020-05-25 09:50:17 +0900310 // Disable packet forwarding
311 if (runner.sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0) {
312 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
313 }
314 if (runner.sysctl_w("net.ipv4.ip_forward", "0") != 0) {
315 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
316 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800317}
318
Garrick Evans4c042572019-12-17 13:42:25 +0900319void Manager::OnSubprocessExited(pid_t pid, const siginfo_t&) {
320 LOG(ERROR) << "Subprocess " << pid << " exited unexpectedly -"
321 << " attempting to restart";
322
323 HelperProcess* proc;
324 if (pid == adb_proxy_->pid()) {
325 proc = adb_proxy_.get();
326 } else if (pid == mcast_proxy_->pid()) {
327 proc = mcast_proxy_.get();
328 } else if (pid == nd_proxy_->pid()) {
329 proc = nd_proxy_.get();
330 } else {
331 LOG(DFATAL) << "Unknown child process";
332 return;
333 }
334
335 process_reaper_.ForgetChild(pid);
336
hschamf9546312020-04-14 15:12:40 +0900337 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Garrick Evans4c042572019-12-17 13:42:25 +0900338 FROM_HERE,
339 base::Bind(&Manager::RestartSubprocess, weak_factory_.GetWeakPtr(), proc),
340 base::TimeDelta::FromMilliseconds((2 << proc->restarts()) *
341 kSubprocessRestartDelayMs));
342}
343
344void Manager::RestartSubprocess(HelperProcess* subproc) {
345 if (subproc->Restart()) {
346 DCHECK(process_reaper_.WatchForChild(
347 FROM_HERE, subproc->pid(),
348 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
349 subproc->pid())))
350 << "Failed to watch child process " << subproc->pid();
351 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800352}
353
Garrick Evanse94a14e2019-11-11 10:32:13 +0900354bool Manager::StartArc(pid_t pid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900355 if (!arc_svc_->Start(pid))
356 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900357
358 GuestMessage msg;
359 msg.set_event(GuestMessage::START);
360 msg.set_type(GuestMessage::ARC);
361 msg.set_arc_pid(pid);
362 SendGuestMessage(msg);
363
364 return true;
365}
366
Garrick Evans21173b12019-11-20 15:23:16 +0900367void Manager::StopArc(pid_t pid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900368 GuestMessage msg;
369 msg.set_event(GuestMessage::STOP);
370 msg.set_type(GuestMessage::ARC);
371 SendGuestMessage(msg);
372
Garrick Evans21173b12019-11-20 15:23:16 +0900373 arc_svc_->Stop(pid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900374}
375
Garrick Evans015b0d62020-02-07 09:06:38 +0900376bool Manager::StartArcVm(uint32_t cid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900377 if (!arc_svc_->Start(cid))
378 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900379
380 GuestMessage msg;
381 msg.set_event(GuestMessage::START);
382 msg.set_type(GuestMessage::ARC_VM);
383 msg.set_arcvm_vsock_cid(cid);
384 SendGuestMessage(msg);
385
386 return true;
387}
388
Garrick Evans015b0d62020-02-07 09:06:38 +0900389void Manager::StopArcVm(uint32_t cid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900390 GuestMessage msg;
391 msg.set_event(GuestMessage::STOP);
392 msg.set_type(GuestMessage::ARC_VM);
393 SendGuestMessage(msg);
394
Garrick Evans21173b12019-11-20 15:23:16 +0900395 arc_svc_->Stop(cid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900396}
397
Garrick Evans51d5b552020-01-30 10:42:06 +0900398bool Manager::StartCrosVm(uint64_t vm_id,
399 GuestMessage::GuestType vm_type,
Garrick Evans53a2a982020-02-05 10:53:35 +0900400 uint32_t subnet_index) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900401 DCHECK(vm_type == GuestMessage::TERMINA_VM ||
402 vm_type == GuestMessage::PLUGIN_VM);
403
404 if (!cros_svc_->Start(vm_id, vm_type == GuestMessage::TERMINA_VM,
405 subnet_index))
Garrick Evans47c19272019-11-21 10:58:21 +0900406 return false;
407
408 GuestMessage msg;
409 msg.set_event(GuestMessage::START);
Garrick Evans51d5b552020-01-30 10:42:06 +0900410 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900411 SendGuestMessage(msg);
412
413 return true;
414}
415
Garrick Evans51d5b552020-01-30 10:42:06 +0900416void Manager::StopCrosVm(uint64_t vm_id, GuestMessage::GuestType vm_type) {
Garrick Evans47c19272019-11-21 10:58:21 +0900417 GuestMessage msg;
418 msg.set_event(GuestMessage::STOP);
Garrick Evans51d5b552020-01-30 10:42:06 +0900419 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900420 SendGuestMessage(msg);
421
Garrick Evans51d5b552020-01-30 10:42:06 +0900422 cros_svc_->Stop(vm_id, vm_type == GuestMessage::TERMINA_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900423}
424
Garrick Evans08843932019-09-17 14:41:08 +0900425std::unique_ptr<dbus::Response> Manager::OnArcStartup(
426 dbus::MethodCall* method_call) {
427 LOG(INFO) << "ARC++ starting up";
428
429 std::unique_ptr<dbus::Response> dbus_response(
430 dbus::Response::FromMethodCall(method_call));
431
432 dbus::MessageReader reader(method_call);
433 dbus::MessageWriter writer(dbus_response.get());
434
435 patchpanel::ArcStartupRequest request;
436 patchpanel::ArcStartupResponse response;
437
438 if (!reader.PopArrayOfBytesAsProto(&request)) {
439 LOG(ERROR) << "Unable to parse request";
440 writer.AppendProtoAsArrayOfBytes(response);
441 return dbus_response;
442 }
443
Garrick Evanse01bf072019-11-15 09:08:19 +0900444 if (!StartArc(request.pid()))
445 LOG(ERROR) << "Failed to start ARC++ network service";
Garrick Evanse94a14e2019-11-11 10:32:13 +0900446
Garrick Evans08843932019-09-17 14:41:08 +0900447 writer.AppendProtoAsArrayOfBytes(response);
448 return dbus_response;
449}
450
451std::unique_ptr<dbus::Response> Manager::OnArcShutdown(
452 dbus::MethodCall* method_call) {
453 LOG(INFO) << "ARC++ shutting down";
454
455 std::unique_ptr<dbus::Response> dbus_response(
456 dbus::Response::FromMethodCall(method_call));
457
458 dbus::MessageReader reader(method_call);
459 dbus::MessageWriter writer(dbus_response.get());
460
461 patchpanel::ArcShutdownRequest request;
462 patchpanel::ArcShutdownResponse response;
463
464 if (!reader.PopArrayOfBytesAsProto(&request)) {
465 LOG(ERROR) << "Unable to parse request";
466 writer.AppendProtoAsArrayOfBytes(response);
467 return dbus_response;
468 }
469
Garrick Evans21173b12019-11-20 15:23:16 +0900470 StopArc(request.pid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900471
Garrick Evans08843932019-09-17 14:41:08 +0900472 writer.AppendProtoAsArrayOfBytes(response);
473 return dbus_response;
474}
475
476std::unique_ptr<dbus::Response> Manager::OnArcVmStartup(
477 dbus::MethodCall* method_call) {
478 LOG(INFO) << "ARCVM starting up";
479
480 std::unique_ptr<dbus::Response> dbus_response(
481 dbus::Response::FromMethodCall(method_call));
482
483 dbus::MessageReader reader(method_call);
484 dbus::MessageWriter writer(dbus_response.get());
485
486 patchpanel::ArcVmStartupRequest request;
487 patchpanel::ArcVmStartupResponse response;
488
489 if (!reader.PopArrayOfBytesAsProto(&request)) {
490 LOG(ERROR) << "Unable to parse request";
491 writer.AppendProtoAsArrayOfBytes(response);
492 return dbus_response;
493 }
494
Garrick Evans47c19272019-11-21 10:58:21 +0900495 if (!StartArcVm(request.cid())) {
Garrick Evanse01bf072019-11-15 09:08:19 +0900496 LOG(ERROR) << "Failed to start ARCVM network service";
Garrick Evans47c19272019-11-21 10:58:21 +0900497 writer.AppendProtoAsArrayOfBytes(response);
498 return dbus_response;
Garrick Evanse01bf072019-11-15 09:08:19 +0900499 }
Garrick Evanse94a14e2019-11-11 10:32:13 +0900500
Garrick Evans47c19272019-11-21 10:58:21 +0900501 // Populate the response with the known devices.
Garrick Evans38b25a42020-04-06 15:17:42 +0900502 for (const auto* config : arc_svc_->GetDeviceConfigs()) {
503 if (config->tap_ifname().empty())
504 continue;
Garrick Evans47c19272019-11-21 10:58:21 +0900505
Garrick Evans38b25a42020-04-06 15:17:42 +0900506 auto* dev = response.add_devices();
507 dev->set_ifname(config->tap_ifname());
508 dev->set_ipv4_addr(config->guest_ipv4_addr());
509 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900510
Garrick Evans08843932019-09-17 14:41:08 +0900511 writer.AppendProtoAsArrayOfBytes(response);
512 return dbus_response;
513}
514
515std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
516 dbus::MethodCall* method_call) {
517 LOG(INFO) << "ARCVM shutting down";
518
519 std::unique_ptr<dbus::Response> dbus_response(
520 dbus::Response::FromMethodCall(method_call));
521
522 dbus::MessageReader reader(method_call);
523 dbus::MessageWriter writer(dbus_response.get());
524
525 patchpanel::ArcVmShutdownRequest request;
526 patchpanel::ArcVmShutdownResponse response;
527
528 if (!reader.PopArrayOfBytesAsProto(&request)) {
529 LOG(ERROR) << "Unable to parse request";
530 writer.AppendProtoAsArrayOfBytes(response);
531 return dbus_response;
532 }
533
Garrick Evans21173b12019-11-20 15:23:16 +0900534 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900535
Garrick Evans08843932019-09-17 14:41:08 +0900536 writer.AppendProtoAsArrayOfBytes(response);
537 return dbus_response;
538}
539
Garrick Evans47c19272019-11-21 10:58:21 +0900540std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
541 dbus::MethodCall* method_call) {
542 LOG(INFO) << "Termina VM starting up";
543
544 std::unique_ptr<dbus::Response> dbus_response(
545 dbus::Response::FromMethodCall(method_call));
546
547 dbus::MessageReader reader(method_call);
548 dbus::MessageWriter writer(dbus_response.get());
549
550 patchpanel::TerminaVmStartupRequest request;
551 patchpanel::TerminaVmStartupResponse response;
552
553 if (!reader.PopArrayOfBytesAsProto(&request)) {
554 LOG(ERROR) << "Unable to parse request";
555 writer.AppendProtoAsArrayOfBytes(response);
556 return dbus_response;
557 }
558
559 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900560 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900561 LOG(ERROR) << "Failed to start Termina VM network service";
562 writer.AppendProtoAsArrayOfBytes(response);
563 return dbus_response;
564 }
565
Garrick Evans51d5b552020-01-30 10:42:06 +0900566 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900567 if (!tap) {
568 LOG(DFATAL) << "TAP device missing";
569 writer.AppendProtoAsArrayOfBytes(response);
570 return dbus_response;
571 }
Garrick Evans47c19272019-11-21 10:58:21 +0900572
Garrick Evansb1c93712020-01-22 09:28:25 +0900573 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900574 dev->set_ifname(tap->host_ifname());
575 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900576 if (!subnet) {
577 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
578 writer.AppendProtoAsArrayOfBytes(response);
579 return dbus_response;
580 }
581 auto* resp_subnet = dev->mutable_ipv4_subnet();
582 resp_subnet->set_base_addr(subnet->BaseAddress());
583 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900584 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900585 if (!subnet) {
586 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
587 writer.AppendProtoAsArrayOfBytes(response);
588 return dbus_response;
589 }
590 resp_subnet = response.mutable_container_subnet();
591 resp_subnet->set_base_addr(subnet->BaseAddress());
592 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900593
594 writer.AppendProtoAsArrayOfBytes(response);
595 return dbus_response;
596}
597
598std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
599 dbus::MethodCall* method_call) {
600 LOG(INFO) << "Termina VM shutting down";
601
602 std::unique_ptr<dbus::Response> dbus_response(
603 dbus::Response::FromMethodCall(method_call));
604
605 dbus::MessageReader reader(method_call);
606 dbus::MessageWriter writer(dbus_response.get());
607
608 patchpanel::TerminaVmShutdownRequest request;
609 patchpanel::TerminaVmShutdownResponse response;
610
611 if (!reader.PopArrayOfBytesAsProto(&request)) {
612 LOG(ERROR) << "Unable to parse request";
613 writer.AppendProtoAsArrayOfBytes(response);
614 return dbus_response;
615 }
616
Garrick Evans51d5b552020-01-30 10:42:06 +0900617 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
618
619 writer.AppendProtoAsArrayOfBytes(response);
620 return dbus_response;
621}
622
623std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
624 dbus::MethodCall* method_call) {
625 LOG(INFO) << "Plugin VM starting up";
626
627 std::unique_ptr<dbus::Response> dbus_response(
628 dbus::Response::FromMethodCall(method_call));
629
630 dbus::MessageReader reader(method_call);
631 dbus::MessageWriter writer(dbus_response.get());
632
633 patchpanel::PluginVmStartupRequest request;
634 patchpanel::PluginVmStartupResponse response;
635
636 if (!reader.PopArrayOfBytesAsProto(&request)) {
637 LOG(ERROR) << "Unable to parse request";
638 writer.AppendProtoAsArrayOfBytes(response);
639 return dbus_response;
640 }
641
Garrick Evans08fb34b2020-02-20 10:50:17 +0900642 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900643 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900644 LOG(ERROR) << "Failed to start Plugin VM network service";
645 writer.AppendProtoAsArrayOfBytes(response);
646 return dbus_response;
647 }
648
649 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
650 if (!tap) {
651 LOG(DFATAL) << "TAP device missing";
652 writer.AppendProtoAsArrayOfBytes(response);
653 return dbus_response;
654 }
655
Garrick Evans51d5b552020-01-30 10:42:06 +0900656 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900657 dev->set_ifname(tap->host_ifname());
658 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900659 if (!subnet) {
660 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
661 writer.AppendProtoAsArrayOfBytes(response);
662 return dbus_response;
663 }
664 auto* resp_subnet = dev->mutable_ipv4_subnet();
665 resp_subnet->set_base_addr(subnet->BaseAddress());
666 resp_subnet->set_prefix_len(subnet->PrefixLength());
667
668 writer.AppendProtoAsArrayOfBytes(response);
669 return dbus_response;
670}
671
672std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
673 dbus::MethodCall* method_call) {
674 LOG(INFO) << "Plugin VM shutting down";
675
676 std::unique_ptr<dbus::Response> dbus_response(
677 dbus::Response::FromMethodCall(method_call));
678
679 dbus::MessageReader reader(method_call);
680 dbus::MessageWriter writer(dbus_response.get());
681
682 patchpanel::PluginVmShutdownRequest request;
683 patchpanel::PluginVmShutdownResponse response;
684
685 if (!reader.PopArrayOfBytesAsProto(&request)) {
686 LOG(ERROR) << "Unable to parse request";
687 writer.AppendProtoAsArrayOfBytes(response);
688 return dbus_response;
689 }
690
691 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900692
693 writer.AppendProtoAsArrayOfBytes(response);
694 return dbus_response;
695}
696
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900697std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
698 dbus::MethodCall* method_call) {
699 std::unique_ptr<dbus::Response> dbus_response(
700 dbus::Response::FromMethodCall(method_call));
701
702 dbus::MessageReader reader(method_call);
703 dbus::MessageWriter writer(dbus_response.get());
704
705 patchpanel::SetVpnIntentRequest request;
706 patchpanel::SetVpnIntentResponse response;
707
708 bool success = reader.PopArrayOfBytesAsProto(&request);
709 if (!success) {
710 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
711 // Do not return yet to make sure we close the received fd.
712 }
713
714 base::ScopedFD client_socket;
715 reader.PopFileDescriptor(&client_socket);
716
717 if (success)
718 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
719
720 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900721
722 writer.AppendProtoAsArrayOfBytes(response);
723 return dbus_response;
724}
725
726std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
727 dbus::MethodCall* method_call) {
728 std::unique_ptr<dbus::Response> dbus_response(
729 dbus::Response::FromMethodCall(method_call));
730
731 dbus::MessageReader reader(method_call);
732 dbus::MessageWriter writer(dbus_response.get());
733
734 patchpanel::ConnectNamespaceRequest request;
735 patchpanel::ConnectNamespaceResponse response;
736
Hugo Benichicc6850f2020-01-17 13:26:06 +0900737 bool success = true;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900738 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900739 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
740 // Do not return yet to make sure we close the received fd and
741 // validate other arguments.
742 success = false;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900743 }
744
Hugo Benichicc6850f2020-01-17 13:26:06 +0900745 base::ScopedFD client_fd;
746 reader.PopFileDescriptor(&client_fd);
747 if (!client_fd.is_valid()) {
748 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
749 success = false;
750 }
751
752 pid_t pid = request.pid();
753 {
754 ScopedNS ns(pid);
755 if (!ns.IsValid()) {
756 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
757 success = false;
758 }
759 }
760
761 const std::string& outbound_ifname = request.outbound_physical_device();
762 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
763 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
764 << outbound_ifname;
765 success = false;
766 }
767
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900768 if (success)
769 ConnectNamespace(std::move(client_fd), request, response);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900770
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900771 writer.AppendProtoAsArrayOfBytes(response);
772 return dbus_response;
773}
774
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900775void Manager::ConnectNamespace(
776 base::ScopedFD client_fd,
777 const patchpanel::ConnectNamespaceRequest& request,
778 patchpanel::ConnectNamespaceResponse& response) {
779 std::unique_ptr<Subnet> subnet =
780 addr_mgr_.AllocateIPv4Subnet(AddressManager::Guest::MINIJAIL_NETNS);
781 if (!subnet) {
782 LOG(ERROR) << "ConnectNamespaceRequest: exhausted IPv4 subnet space";
783 return;
784 }
785
786 const std::string ifname_id = std::to_string(connected_namespaces_next_id_);
787 const std::string host_ifname = "arc_ns" + ifname_id;
788 const std::string client_ifname = "veth" + ifname_id;
Hugo Benichie8758b52020-04-03 14:49:01 +0900789 const uint32_t host_ipv4_addr = subnet->AddressAtOffset(0);
790 const uint32_t client_ipv4_addr = subnet->AddressAtOffset(1);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900791
Hugo Benichie8758b52020-04-03 14:49:01 +0900792 // Veth interface configuration and client routing configuration:
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900793 // - create veth pair inside client namespace.
794 // - configure IPv4 address on remote veth inside client namespace.
Hugo Benichie8758b52020-04-03 14:49:01 +0900795 // - configure IPv4 address on local veth inside host namespace.
796 // - add a default IPv4 /0 route sending traffic to that remote veth.
797 // - bring back one veth to the host namespace, and set it up.
798 pid_t pid = request.pid();
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900799 if (!datapath_->ConnectVethPair(pid, host_ifname, client_ifname,
800 addr_mgr_.GenerateMacAddress(),
801 client_ipv4_addr, subnet->PrefixLength(),
802 false /* enable_multicast */)) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900803 LOG(ERROR) << "ConnectNamespaceRequest: failed to create veth pair for "
804 "namespace pid "
805 << pid;
806 return;
807 }
808 if (!datapath_->ConfigureInterface(
809 host_ifname, addr_mgr_.GenerateMacAddress(), host_ipv4_addr,
810 subnet->PrefixLength(), true /* link up */,
811 false /* enable_multicast */)) {
812 LOG(ERROR) << "ConnectNamespaceRequest: cannot configure host interface "
813 << host_ifname;
814 datapath_->RemoveInterface(host_ifname);
815 return;
816 }
817 {
818 ScopedNS ns(pid);
819 if (!ns.IsValid()) {
820 LOG(ERROR) << "ConnectNamespaceRequest: cannot enter client pid " << pid;
821 datapath_->RemoveInterface(host_ifname);
822 return;
823 }
824 if (!datapath_->AddIPv4Route(host_ipv4_addr, INADDR_ANY, INADDR_ANY)) {
825 LOG(ERROR)
826 << "ConnectNamespaceRequest: failed to add default /0 route to "
827 << host_ifname << " inside namespace pid " << pid;
828 datapath_->RemoveInterface(host_ifname);
829 return;
830 }
831 }
832
833 // Host namespace routing configuration
834 // - ingress: add route to client subnet via |host_ifname|.
835 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
836 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
837 // Note that by default unsolicited ingress traffic is not forwarded to the
838 // client namespace unless the client specifically set port forwarding
839 // through permission_broker DBus APIs.
840 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
841 // both ways between client namespace and other guest containers and VMs.
842 // TODO(hugobenichi) If outbound_physical_device is defined, then set strong
843 // routing to that interface routing table.
844 if (!datapath_->AddIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
845 subnet->Netmask())) {
846 LOG(ERROR)
847 << "ConnectNamespaceRequest: failed to set route to client namespace";
848 datapath_->RemoveInterface(host_ifname);
849 return;
850 }
851 if (!datapath_->AddOutboundIPv4(host_ifname)) {
852 LOG(ERROR) << "ConnectNamespaceRequest: failed to allow FORWARD for "
853 "traffic outgoing from "
854 << host_ifname;
855 datapath_->RemoveInterface(host_ifname);
856 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
857 subnet->Netmask());
858 return;
859 }
860 if (!datapath_->AddOutboundIPv4SNATMark(host_ifname)) {
861 LOG(ERROR) << "ConnectNamespaceRequest: failed to set SNAT for traffic "
862 "outgoing from "
863 << host_ifname;
864 datapath_->RemoveInterface(host_ifname);
865 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
866 subnet->Netmask());
867 datapath_->RemoveOutboundIPv4(host_ifname);
868 return;
869 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900870
Hugo Benichi7352ad92020-04-07 16:11:59 +0900871 // Dup the client fd into our own: this guarantees that the fd number will
872 // be stable and tied to the actual kernel resources used by the client.
873 base::ScopedFD local_client_fd(dup(client_fd.get()));
874 if (!local_client_fd.is_valid()) {
875 PLOG(ERROR) << "ConnectNamespaceRequest: failed to dup() client fd";
Hugo Benichie8758b52020-04-03 14:49:01 +0900876 datapath_->RemoveInterface(host_ifname);
877 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
878 subnet->Netmask());
879 datapath_->RemoveOutboundIPv4(host_ifname);
880 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900881 return;
882 }
883
884 // Add the dupe fd to the epoll watcher.
885 // TODO(hugobenichi) Find a way to reuse base::FileDescriptorWatcher for
886 // listening to EPOLLHUP.
887 struct epoll_event epevent;
888 epevent.events = EPOLLIN; // EPOLLERR | EPOLLHUP are always waited for.
889 epevent.data.fd = local_client_fd.get();
890 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_ADD,
891 local_client_fd.get(), &epevent) != 0) {
892 PLOG(ERROR) << "ConnectNamespaceResponse: epoll_ctl(EPOLL_CTL_ADD) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900893 datapath_->RemoveInterface(host_ifname);
894 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
895 subnet->Netmask());
896 datapath_->RemoveOutboundIPv4(host_ifname);
897 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900898 return;
899 }
900
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900901 // Prepare the response before storing ConnectNamespaceInfo.
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900902 response.set_peer_ifname(client_ifname);
903 response.set_peer_ipv4_address(host_ipv4_addr);
904 response.set_host_ifname(host_ifname);
905 response.set_host_ipv4_address(client_ipv4_addr);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900906 auto* response_subnet = response.mutable_ipv4_subnet();
907 response_subnet->set_base_addr(subnet->BaseAddress());
908 response_subnet->set_prefix_len(subnet->PrefixLength());
909
910 // Store ConnectNamespaceInfo
911 connected_namespaces_next_id_++;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900912 int fdkey = local_client_fd.release();
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900913 connected_namespaces_[fdkey] = {};
914 ConnectNamespaceInfo& ns_info = connected_namespaces_[fdkey];
915 ns_info.pid = request.pid();
916 ns_info.outbound_ifname = request.outbound_physical_device();
917 ns_info.host_ifname = std::move(host_ifname);
918 ns_info.client_ifname = std::move(client_ifname);
919 ns_info.client_subnet = std::move(subnet);
920
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900921 LOG(INFO) << "Connected network namespace " << ns_info;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900922
923 if (connected_namespaces_.size() == 1) {
924 LOG(INFO) << "Starting ConnectNamespace client fds monitoring";
925 CheckConnectedNamespaces();
926 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900927}
928
929void Manager::DisconnectNamespace(int client_fd) {
930 auto it = connected_namespaces_.find(client_fd);
931 if (it == connected_namespaces_.end()) {
932 LOG(ERROR) << "No ConnectNamespaceInfo found for client_fd " << client_fd;
933 return;
934 }
935
Hugo Benichi7352ad92020-04-07 16:11:59 +0900936 // Remove the client fd dupe from the epoll watcher and close it.
937 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL, client_fd,
Hugo Benichie8758b52020-04-03 14:49:01 +0900938 nullptr) != 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900939 PLOG(ERROR) << "DisconnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900940 if (close(client_fd) < 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900941 PLOG(ERROR) << "DisconnectNamespace: close(client_fd) failed";
Hugo Benichi7352ad92020-04-07 16:11:59 +0900942
Hugo Benichie8758b52020-04-03 14:49:01 +0900943 // Destroy the interface configuration and routing configuration:
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900944 // - destroy veth pair.
Hugo Benichie8758b52020-04-03 14:49:01 +0900945 // - remove forwarding rules on host namespace.
946 // - remove SNAT marking rule on host namespace.
947 // Note that the default route set inside the client namespace by patchpanel
948 // is not destroyed: it is assumed the client will also teardown its
949 // namespace if it triggered DisconnectNamespace.
950 datapath_->RemoveInterface(it->second.host_ifname);
951 datapath_->RemoveOutboundIPv4(it->second.host_ifname);
952 datapath_->RemoveOutboundIPv4SNATMark(it->second.host_ifname);
953 datapath_->DeleteIPv4Route(it->second.client_subnet->AddressAtOffset(0),
954 it->second.client_subnet->BaseAddress(),
955 it->second.client_subnet->Netmask());
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900956
957 LOG(INFO) << "Disconnected network namespace " << it->second;
958
959 // This release the allocated IPv4 subnet.
960 connected_namespaces_.erase(it);
961}
962
Hugo Benichi7352ad92020-04-07 16:11:59 +0900963// TODO(hugobenichi) Generalize this check to all resources created by
964// patchpanel on behalf of a remote client.
965void Manager::CheckConnectedNamespaces() {
966 int max_event = 10;
967 struct epoll_event epevents[max_event];
968 int nready = epoll_wait(connected_namespaces_epollfd_, epevents, max_event,
969 0 /* do not block */);
970 if (nready < 0)
971 PLOG(ERROR) << "CheckConnectedNamespaces: epoll_wait(0) failed";
972
973 for (int i = 0; i < nready; i++)
974 if (epevents[i].events & (EPOLLHUP | EPOLLERR))
975 DisconnectNamespace(epevents[i].data.fd);
976
977 if (connected_namespaces_.empty()) {
978 LOG(INFO) << "Stopping ConnectNamespace client fds monitoring";
979 return;
980 }
981
Qijiang Fan2d7aeb42020-05-19 02:06:39 +0900982 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Hugo Benichi7352ad92020-04-07 16:11:59 +0900983 FROM_HERE,
984 base::Bind(&Manager::CheckConnectedNamespaces,
Hugo Benichie8758b52020-04-03 14:49:01 +0900985 weak_factory_.GetWeakPtr()),
Hugo Benichi7352ad92020-04-07 16:11:59 +0900986 kConnectNamespaceCheckInterval);
987}
988
Garrick Evanse94a14e2019-11-11 10:32:13 +0900989void Manager::SendGuestMessage(const GuestMessage& msg) {
Garrick Evans96e03042019-05-28 14:30:52 +0900990 IpHelperMessage ipm;
991 *ipm.mutable_guest_message() = msg;
Garrick Evans96e03042019-05-28 14:30:52 +0900992 adb_proxy_->SendMessage(ipm);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900993 mcast_proxy_->SendMessage(ipm);
994 nd_proxy_->SendMessage(ipm);
Garrick Evans96e03042019-05-28 14:30:52 +0900995}
996
Garrick Evans4ac09852020-01-16 14:09:22 +0900997void Manager::StartForwarding(const std::string& ifname_physical,
998 const std::string& ifname_virtual,
Garrick Evans4ac09852020-01-16 14:09:22 +0900999 bool ipv6,
1000 bool multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001001 if (ifname_physical.empty() || ifname_virtual.empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001002 return;
1003
1004 IpHelperMessage ipm;
1005 DeviceMessage* msg = ipm.mutable_device_message();
1006 msg->set_dev_ifname(ifname_physical);
Garrick Evans4ac09852020-01-16 14:09:22 +09001007 msg->set_br_ifname(ifname_virtual);
1008
1009 if (ipv6) {
1010 LOG(INFO) << "Starting IPv6 forwarding from " << ifname_physical << " to "
1011 << ifname_virtual;
1012
1013 if (!datapath_->AddIPv6Forwarding(ifname_physical, ifname_virtual)) {
1014 LOG(ERROR) << "Failed to setup iptables forwarding rule for IPv6 from "
1015 << ifname_physical << " to " << ifname_virtual;
1016 }
1017 if (!datapath_->MaskInterfaceFlags(ifname_physical, IFF_ALLMULTI)) {
1018 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1019 << ifname_physical;
1020 }
1021 if (!datapath_->MaskInterfaceFlags(ifname_virtual, IFF_ALLMULTI)) {
1022 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1023 << ifname_virtual;
1024 }
1025 nd_proxy_->SendMessage(ipm);
1026 }
1027
1028 if (multicast) {
1029 LOG(INFO) << "Starting multicast forwarding from " << ifname_physical
1030 << " to " << ifname_virtual;
1031 mcast_proxy_->SendMessage(ipm);
1032 }
1033}
1034
1035void Manager::StopForwarding(const std::string& ifname_physical,
1036 const std::string& ifname_virtual,
1037 bool ipv6,
1038 bool multicast) {
1039 if (ifname_physical.empty())
1040 return;
1041
1042 IpHelperMessage ipm;
1043 DeviceMessage* msg = ipm.mutable_device_message();
1044 msg->set_dev_ifname(ifname_physical);
1045 msg->set_teardown(true);
Taoyu Li7dca19a2020-03-16 16:27:07 +09001046 if (!ifname_virtual.empty()) {
1047 msg->set_br_ifname(ifname_virtual);
1048 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001049
1050 if (ipv6) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001051 if (ifname_virtual.empty()) {
1052 LOG(INFO) << "Stopping IPv6 forwarding on " << ifname_physical;
1053 } else {
1054 LOG(INFO) << "Stopping IPv6 forwarding from " << ifname_physical << " to "
1055 << ifname_virtual;
1056 datapath_->RemoveIPv6Forwarding(ifname_physical, ifname_virtual);
1057 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001058 nd_proxy_->SendMessage(ipm);
1059 }
1060
1061 if (multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001062 if (ifname_virtual.empty()) {
1063 LOG(INFO) << "Stopping multicast forwarding on " << ifname_physical;
1064 } else {
1065 LOG(INFO) << "Stopping multicast forwarding from " << ifname_physical
1066 << " to " << ifname_virtual;
1067 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001068 mcast_proxy_->SendMessage(ipm);
1069 }
1070}
1071
Garrick Evans4ac09852020-01-16 14:09:22 +09001072void Manager::OnDeviceMessageFromNDProxy(const DeviceMessage& msg) {
1073 LOG_IF(DFATAL, msg.dev_ifname().empty())
1074 << "Received DeviceMessage w/ empty dev_ifname";
1075
1076 if (!datapath_->AddIPv6HostRoute(msg.dev_ifname(), msg.guest_ip6addr(),
1077 128)) {
1078 LOG(WARNING) << "Failed to setup the IPv6 route for interface "
1079 << msg.dev_ifname();
1080 }
1081}
1082
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001083std::ostream& operator<<(std::ostream& stream,
1084 const Manager::ConnectNamespaceInfo& ns_info) {
1085 stream << "{ pid: " << ns_info.pid;
1086 if (!ns_info.outbound_ifname.empty()) {
1087 stream << ", outbound_ifname: " << ns_info.outbound_ifname;
1088 }
1089 stream << ", host_ifname: " << ns_info.host_ifname
1090 << ", client_ifname: " << ns_info.client_ifname
1091 << ", subnet: " << ns_info.client_subnet->ToCidrString() << '}';
1092 return stream;
1093}
1094
Garrick Evans3388a032020-03-24 11:25:55 +09001095} // namespace patchpanel