blob: c77cf032d9bdce96af44f7776ffc0380029b78ff [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
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900264 routing_svc_ = std::make_unique<RoutingService>();
265
Garrick Evans4ac09852020-01-16 14:09:22 +0900266 nd_proxy_->RegisterDeviceMessageHandler(base::Bind(
267 &Manager::OnDeviceMessageFromNDProxy, weak_factory_.GetWeakPtr()));
268
Garrick Evans69b85872020-02-04 11:40:26 +0900269 shill_client_ = std::make_unique<ShillClient>(bus_);
Garrick Evans1b1f67c2020-02-04 16:21:25 +0900270 auto* const forwarder = static_cast<TrafficForwarder*>(this);
Garrick Evans5d55f5e2019-07-17 15:28:10 +0900271
Garrick Evansf5862122020-03-16 09:13:45 +0900272 arc_svc_ = std::make_unique<ArcService>(
273 shill_client_.get(), datapath_.get(), &addr_mgr_, forwarder,
274 ShouldEnableFeature(kArcVmMultinetMinAndroidSdkVersion,
275 kArcVmMultinetMinChromeMilestone, {},
276 kArcVmMultinetFeatureName));
Garrick Evans1b1f67c2020-02-04 16:21:25 +0900277 cros_svc_ = std::make_unique<CrostiniService>(shill_client_.get(), &addr_mgr_,
278 datapath_.get(), forwarder);
Taoyu Liaf944c92019-10-01 12:22:31 +0900279
280 nd_proxy_->Listen();
Long Chengd4415582019-09-24 19:16:09 +0000281}
Garrick Evans49879532018-12-03 13:15:36 +0900282
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800283void Manager::OnShutdown(int* exit_code) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900284 LOG(INFO) << "Shutting down and cleaning up";
Garrick Evans207e7482019-12-16 11:54:36 +0900285 cros_svc_.reset();
286 arc_svc_.reset();
Hugo Benichi7352ad92020-04-07 16:11:59 +0900287 close(connected_namespaces_epollfd_);
Hugo Benichie8758b52020-04-03 14:49:01 +0900288 // Tear down any remaining connected namespace.
289 std::vector<int> connected_namespaces_fdkeys;
290 for (const auto& kv : connected_namespaces_)
291 connected_namespaces_fdkeys.push_back(kv.first);
292 for (const int fdkey : connected_namespaces_fdkeys)
293 DisconnectNamespace(fdkey);
Garrick Evans28d194e2019-12-17 10:22:28 +0900294
Garrick Evansff6e37f2020-05-25 10:54:47 +0900295 datapath_->RemoveInterfaceSNAT("wwan+");
Garrick Evansd291af62020-05-25 10:39:06 +0900296 datapath_->RemoveForwardEstablishedRule();
297 datapath_->RemoveSNATMarkRules();
298
Garrick Evans7cf8c542020-05-25 09:50:17 +0900299 auto& runner = datapath_->runner();
Garrick Evans28d194e2019-12-17 10:22:28 +0900300 // Restore original local port range.
301 // TODO(garrick): The original history behind this tweak is gone. Some
302 // investigation is needed to see if it is still applicable.
Garrick Evans7cf8c542020-05-25 09:50:17 +0900303 if (runner.sysctl_w("net.ipv4.ip_local_port_range", "32768 61000") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900304 LOG(ERROR) << "Failed to restore local port range";
305 }
Garrick Evans7cf8c542020-05-25 09:50:17 +0900306 // Disable packet forwarding
307 if (runner.sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0) {
308 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
309 }
310 if (runner.sysctl_w("net.ipv4.ip_forward", "0") != 0) {
311 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
312 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800313}
314
Garrick Evans4c042572019-12-17 13:42:25 +0900315void Manager::OnSubprocessExited(pid_t pid, const siginfo_t&) {
316 LOG(ERROR) << "Subprocess " << pid << " exited unexpectedly -"
317 << " attempting to restart";
318
319 HelperProcess* proc;
320 if (pid == adb_proxy_->pid()) {
321 proc = adb_proxy_.get();
322 } else if (pid == mcast_proxy_->pid()) {
323 proc = mcast_proxy_.get();
324 } else if (pid == nd_proxy_->pid()) {
325 proc = nd_proxy_.get();
326 } else {
327 LOG(DFATAL) << "Unknown child process";
328 return;
329 }
330
331 process_reaper_.ForgetChild(pid);
332
hschamf9546312020-04-14 15:12:40 +0900333 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Garrick Evans4c042572019-12-17 13:42:25 +0900334 FROM_HERE,
335 base::Bind(&Manager::RestartSubprocess, weak_factory_.GetWeakPtr(), proc),
336 base::TimeDelta::FromMilliseconds((2 << proc->restarts()) *
337 kSubprocessRestartDelayMs));
338}
339
340void Manager::RestartSubprocess(HelperProcess* subproc) {
341 if (subproc->Restart()) {
342 DCHECK(process_reaper_.WatchForChild(
343 FROM_HERE, subproc->pid(),
344 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
345 subproc->pid())))
346 << "Failed to watch child process " << subproc->pid();
347 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800348}
349
Garrick Evanse94a14e2019-11-11 10:32:13 +0900350bool Manager::StartArc(pid_t pid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900351 if (!arc_svc_->Start(pid))
352 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900353
354 GuestMessage msg;
355 msg.set_event(GuestMessage::START);
356 msg.set_type(GuestMessage::ARC);
357 msg.set_arc_pid(pid);
358 SendGuestMessage(msg);
359
360 return true;
361}
362
Garrick Evans21173b12019-11-20 15:23:16 +0900363void Manager::StopArc(pid_t pid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900364 GuestMessage msg;
365 msg.set_event(GuestMessage::STOP);
366 msg.set_type(GuestMessage::ARC);
367 SendGuestMessage(msg);
368
Garrick Evans21173b12019-11-20 15:23:16 +0900369 arc_svc_->Stop(pid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900370}
371
Garrick Evans015b0d62020-02-07 09:06:38 +0900372bool Manager::StartArcVm(uint32_t cid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900373 if (!arc_svc_->Start(cid))
374 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900375
376 GuestMessage msg;
377 msg.set_event(GuestMessage::START);
378 msg.set_type(GuestMessage::ARC_VM);
379 msg.set_arcvm_vsock_cid(cid);
380 SendGuestMessage(msg);
381
382 return true;
383}
384
Garrick Evans015b0d62020-02-07 09:06:38 +0900385void Manager::StopArcVm(uint32_t cid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900386 GuestMessage msg;
387 msg.set_event(GuestMessage::STOP);
388 msg.set_type(GuestMessage::ARC_VM);
389 SendGuestMessage(msg);
390
Garrick Evans21173b12019-11-20 15:23:16 +0900391 arc_svc_->Stop(cid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900392}
393
Garrick Evans51d5b552020-01-30 10:42:06 +0900394bool Manager::StartCrosVm(uint64_t vm_id,
395 GuestMessage::GuestType vm_type,
Garrick Evans53a2a982020-02-05 10:53:35 +0900396 uint32_t subnet_index) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900397 DCHECK(vm_type == GuestMessage::TERMINA_VM ||
398 vm_type == GuestMessage::PLUGIN_VM);
399
400 if (!cros_svc_->Start(vm_id, vm_type == GuestMessage::TERMINA_VM,
401 subnet_index))
Garrick Evans47c19272019-11-21 10:58:21 +0900402 return false;
403
404 GuestMessage msg;
405 msg.set_event(GuestMessage::START);
Garrick Evans51d5b552020-01-30 10:42:06 +0900406 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900407 SendGuestMessage(msg);
408
409 return true;
410}
411
Garrick Evans51d5b552020-01-30 10:42:06 +0900412void Manager::StopCrosVm(uint64_t vm_id, GuestMessage::GuestType vm_type) {
Garrick Evans47c19272019-11-21 10:58:21 +0900413 GuestMessage msg;
414 msg.set_event(GuestMessage::STOP);
Garrick Evans51d5b552020-01-30 10:42:06 +0900415 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900416 SendGuestMessage(msg);
417
Garrick Evans51d5b552020-01-30 10:42:06 +0900418 cros_svc_->Stop(vm_id, vm_type == GuestMessage::TERMINA_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900419}
420
Garrick Evans08843932019-09-17 14:41:08 +0900421std::unique_ptr<dbus::Response> Manager::OnArcStartup(
422 dbus::MethodCall* method_call) {
423 LOG(INFO) << "ARC++ starting up";
424
425 std::unique_ptr<dbus::Response> dbus_response(
426 dbus::Response::FromMethodCall(method_call));
427
428 dbus::MessageReader reader(method_call);
429 dbus::MessageWriter writer(dbus_response.get());
430
431 patchpanel::ArcStartupRequest request;
432 patchpanel::ArcStartupResponse response;
433
434 if (!reader.PopArrayOfBytesAsProto(&request)) {
435 LOG(ERROR) << "Unable to parse request";
436 writer.AppendProtoAsArrayOfBytes(response);
437 return dbus_response;
438 }
439
Garrick Evanse01bf072019-11-15 09:08:19 +0900440 if (!StartArc(request.pid()))
441 LOG(ERROR) << "Failed to start ARC++ network service";
Garrick Evanse94a14e2019-11-11 10:32:13 +0900442
Garrick Evans08843932019-09-17 14:41:08 +0900443 writer.AppendProtoAsArrayOfBytes(response);
444 return dbus_response;
445}
446
447std::unique_ptr<dbus::Response> Manager::OnArcShutdown(
448 dbus::MethodCall* method_call) {
449 LOG(INFO) << "ARC++ shutting down";
450
451 std::unique_ptr<dbus::Response> dbus_response(
452 dbus::Response::FromMethodCall(method_call));
453
454 dbus::MessageReader reader(method_call);
455 dbus::MessageWriter writer(dbus_response.get());
456
457 patchpanel::ArcShutdownRequest request;
458 patchpanel::ArcShutdownResponse response;
459
460 if (!reader.PopArrayOfBytesAsProto(&request)) {
461 LOG(ERROR) << "Unable to parse request";
462 writer.AppendProtoAsArrayOfBytes(response);
463 return dbus_response;
464 }
465
Garrick Evans21173b12019-11-20 15:23:16 +0900466 StopArc(request.pid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900467
Garrick Evans08843932019-09-17 14:41:08 +0900468 writer.AppendProtoAsArrayOfBytes(response);
469 return dbus_response;
470}
471
472std::unique_ptr<dbus::Response> Manager::OnArcVmStartup(
473 dbus::MethodCall* method_call) {
474 LOG(INFO) << "ARCVM starting up";
475
476 std::unique_ptr<dbus::Response> dbus_response(
477 dbus::Response::FromMethodCall(method_call));
478
479 dbus::MessageReader reader(method_call);
480 dbus::MessageWriter writer(dbus_response.get());
481
482 patchpanel::ArcVmStartupRequest request;
483 patchpanel::ArcVmStartupResponse response;
484
485 if (!reader.PopArrayOfBytesAsProto(&request)) {
486 LOG(ERROR) << "Unable to parse request";
487 writer.AppendProtoAsArrayOfBytes(response);
488 return dbus_response;
489 }
490
Garrick Evans47c19272019-11-21 10:58:21 +0900491 if (!StartArcVm(request.cid())) {
Garrick Evanse01bf072019-11-15 09:08:19 +0900492 LOG(ERROR) << "Failed to start ARCVM network service";
Garrick Evans47c19272019-11-21 10:58:21 +0900493 writer.AppendProtoAsArrayOfBytes(response);
494 return dbus_response;
Garrick Evanse01bf072019-11-15 09:08:19 +0900495 }
Garrick Evanse94a14e2019-11-11 10:32:13 +0900496
Garrick Evans47c19272019-11-21 10:58:21 +0900497 // Populate the response with the known devices.
Garrick Evans38b25a42020-04-06 15:17:42 +0900498 for (const auto* config : arc_svc_->GetDeviceConfigs()) {
499 if (config->tap_ifname().empty())
500 continue;
Garrick Evans47c19272019-11-21 10:58:21 +0900501
Garrick Evans38b25a42020-04-06 15:17:42 +0900502 auto* dev = response.add_devices();
503 dev->set_ifname(config->tap_ifname());
504 dev->set_ipv4_addr(config->guest_ipv4_addr());
505 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900506
Garrick Evans08843932019-09-17 14:41:08 +0900507 writer.AppendProtoAsArrayOfBytes(response);
508 return dbus_response;
509}
510
511std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
512 dbus::MethodCall* method_call) {
513 LOG(INFO) << "ARCVM shutting down";
514
515 std::unique_ptr<dbus::Response> dbus_response(
516 dbus::Response::FromMethodCall(method_call));
517
518 dbus::MessageReader reader(method_call);
519 dbus::MessageWriter writer(dbus_response.get());
520
521 patchpanel::ArcVmShutdownRequest request;
522 patchpanel::ArcVmShutdownResponse response;
523
524 if (!reader.PopArrayOfBytesAsProto(&request)) {
525 LOG(ERROR) << "Unable to parse request";
526 writer.AppendProtoAsArrayOfBytes(response);
527 return dbus_response;
528 }
529
Garrick Evans21173b12019-11-20 15:23:16 +0900530 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900531
Garrick Evans08843932019-09-17 14:41:08 +0900532 writer.AppendProtoAsArrayOfBytes(response);
533 return dbus_response;
534}
535
Garrick Evans47c19272019-11-21 10:58:21 +0900536std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
537 dbus::MethodCall* method_call) {
538 LOG(INFO) << "Termina VM starting up";
539
540 std::unique_ptr<dbus::Response> dbus_response(
541 dbus::Response::FromMethodCall(method_call));
542
543 dbus::MessageReader reader(method_call);
544 dbus::MessageWriter writer(dbus_response.get());
545
546 patchpanel::TerminaVmStartupRequest request;
547 patchpanel::TerminaVmStartupResponse response;
548
549 if (!reader.PopArrayOfBytesAsProto(&request)) {
550 LOG(ERROR) << "Unable to parse request";
551 writer.AppendProtoAsArrayOfBytes(response);
552 return dbus_response;
553 }
554
555 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900556 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900557 LOG(ERROR) << "Failed to start Termina VM network service";
558 writer.AppendProtoAsArrayOfBytes(response);
559 return dbus_response;
560 }
561
Garrick Evans51d5b552020-01-30 10:42:06 +0900562 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900563 if (!tap) {
564 LOG(DFATAL) << "TAP device missing";
565 writer.AppendProtoAsArrayOfBytes(response);
566 return dbus_response;
567 }
Garrick Evans47c19272019-11-21 10:58:21 +0900568
Garrick Evansb1c93712020-01-22 09:28:25 +0900569 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900570 dev->set_ifname(tap->host_ifname());
571 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900572 if (!subnet) {
573 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
574 writer.AppendProtoAsArrayOfBytes(response);
575 return dbus_response;
576 }
577 auto* resp_subnet = dev->mutable_ipv4_subnet();
578 resp_subnet->set_base_addr(subnet->BaseAddress());
579 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900580 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900581 if (!subnet) {
582 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
583 writer.AppendProtoAsArrayOfBytes(response);
584 return dbus_response;
585 }
586 resp_subnet = response.mutable_container_subnet();
587 resp_subnet->set_base_addr(subnet->BaseAddress());
588 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900589
590 writer.AppendProtoAsArrayOfBytes(response);
591 return dbus_response;
592}
593
594std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
595 dbus::MethodCall* method_call) {
596 LOG(INFO) << "Termina VM shutting down";
597
598 std::unique_ptr<dbus::Response> dbus_response(
599 dbus::Response::FromMethodCall(method_call));
600
601 dbus::MessageReader reader(method_call);
602 dbus::MessageWriter writer(dbus_response.get());
603
604 patchpanel::TerminaVmShutdownRequest request;
605 patchpanel::TerminaVmShutdownResponse response;
606
607 if (!reader.PopArrayOfBytesAsProto(&request)) {
608 LOG(ERROR) << "Unable to parse request";
609 writer.AppendProtoAsArrayOfBytes(response);
610 return dbus_response;
611 }
612
Garrick Evans51d5b552020-01-30 10:42:06 +0900613 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
614
615 writer.AppendProtoAsArrayOfBytes(response);
616 return dbus_response;
617}
618
619std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
620 dbus::MethodCall* method_call) {
621 LOG(INFO) << "Plugin VM starting up";
622
623 std::unique_ptr<dbus::Response> dbus_response(
624 dbus::Response::FromMethodCall(method_call));
625
626 dbus::MessageReader reader(method_call);
627 dbus::MessageWriter writer(dbus_response.get());
628
629 patchpanel::PluginVmStartupRequest request;
630 patchpanel::PluginVmStartupResponse response;
631
632 if (!reader.PopArrayOfBytesAsProto(&request)) {
633 LOG(ERROR) << "Unable to parse request";
634 writer.AppendProtoAsArrayOfBytes(response);
635 return dbus_response;
636 }
637
Garrick Evans08fb34b2020-02-20 10:50:17 +0900638 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900639 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900640 LOG(ERROR) << "Failed to start Plugin VM network service";
641 writer.AppendProtoAsArrayOfBytes(response);
642 return dbus_response;
643 }
644
645 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
646 if (!tap) {
647 LOG(DFATAL) << "TAP device missing";
648 writer.AppendProtoAsArrayOfBytes(response);
649 return dbus_response;
650 }
651
Garrick Evans51d5b552020-01-30 10:42:06 +0900652 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900653 dev->set_ifname(tap->host_ifname());
654 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900655 if (!subnet) {
656 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
657 writer.AppendProtoAsArrayOfBytes(response);
658 return dbus_response;
659 }
660 auto* resp_subnet = dev->mutable_ipv4_subnet();
661 resp_subnet->set_base_addr(subnet->BaseAddress());
662 resp_subnet->set_prefix_len(subnet->PrefixLength());
663
664 writer.AppendProtoAsArrayOfBytes(response);
665 return dbus_response;
666}
667
668std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
669 dbus::MethodCall* method_call) {
670 LOG(INFO) << "Plugin VM shutting down";
671
672 std::unique_ptr<dbus::Response> dbus_response(
673 dbus::Response::FromMethodCall(method_call));
674
675 dbus::MessageReader reader(method_call);
676 dbus::MessageWriter writer(dbus_response.get());
677
678 patchpanel::PluginVmShutdownRequest request;
679 patchpanel::PluginVmShutdownResponse response;
680
681 if (!reader.PopArrayOfBytesAsProto(&request)) {
682 LOG(ERROR) << "Unable to parse request";
683 writer.AppendProtoAsArrayOfBytes(response);
684 return dbus_response;
685 }
686
687 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900688
689 writer.AppendProtoAsArrayOfBytes(response);
690 return dbus_response;
691}
692
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900693std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
694 dbus::MethodCall* method_call) {
695 std::unique_ptr<dbus::Response> dbus_response(
696 dbus::Response::FromMethodCall(method_call));
697
698 dbus::MessageReader reader(method_call);
699 dbus::MessageWriter writer(dbus_response.get());
700
701 patchpanel::SetVpnIntentRequest request;
702 patchpanel::SetVpnIntentResponse response;
703
704 bool success = reader.PopArrayOfBytesAsProto(&request);
705 if (!success) {
706 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
707 // Do not return yet to make sure we close the received fd.
708 }
709
710 base::ScopedFD client_socket;
711 reader.PopFileDescriptor(&client_socket);
712
713 if (success)
714 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
715
716 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900717
718 writer.AppendProtoAsArrayOfBytes(response);
719 return dbus_response;
720}
721
722std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
723 dbus::MethodCall* method_call) {
724 std::unique_ptr<dbus::Response> dbus_response(
725 dbus::Response::FromMethodCall(method_call));
726
727 dbus::MessageReader reader(method_call);
728 dbus::MessageWriter writer(dbus_response.get());
729
730 patchpanel::ConnectNamespaceRequest request;
731 patchpanel::ConnectNamespaceResponse response;
732
Hugo Benichicc6850f2020-01-17 13:26:06 +0900733 bool success = true;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900734 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900735 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
736 // Do not return yet to make sure we close the received fd and
737 // validate other arguments.
738 success = false;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900739 }
740
Hugo Benichicc6850f2020-01-17 13:26:06 +0900741 base::ScopedFD client_fd;
742 reader.PopFileDescriptor(&client_fd);
743 if (!client_fd.is_valid()) {
744 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
745 success = false;
746 }
747
748 pid_t pid = request.pid();
749 {
750 ScopedNS ns(pid);
751 if (!ns.IsValid()) {
752 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
753 success = false;
754 }
755 }
756
757 const std::string& outbound_ifname = request.outbound_physical_device();
758 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
759 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
760 << outbound_ifname;
761 success = false;
762 }
763
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900764 if (success)
765 ConnectNamespace(std::move(client_fd), request, response);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900766
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900767 writer.AppendProtoAsArrayOfBytes(response);
768 return dbus_response;
769}
770
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900771void Manager::ConnectNamespace(
772 base::ScopedFD client_fd,
773 const patchpanel::ConnectNamespaceRequest& request,
774 patchpanel::ConnectNamespaceResponse& response) {
775 std::unique_ptr<Subnet> subnet =
776 addr_mgr_.AllocateIPv4Subnet(AddressManager::Guest::MINIJAIL_NETNS);
777 if (!subnet) {
778 LOG(ERROR) << "ConnectNamespaceRequest: exhausted IPv4 subnet space";
779 return;
780 }
781
782 const std::string ifname_id = std::to_string(connected_namespaces_next_id_);
783 const std::string host_ifname = "arc_ns" + ifname_id;
784 const std::string client_ifname = "veth" + ifname_id;
Hugo Benichie8758b52020-04-03 14:49:01 +0900785 const uint32_t host_ipv4_addr = subnet->AddressAtOffset(0);
786 const uint32_t client_ipv4_addr = subnet->AddressAtOffset(1);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900787
Hugo Benichie8758b52020-04-03 14:49:01 +0900788 // Veth interface configuration and client routing configuration:
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900789 // - create veth pair inside client namespace.
790 // - configure IPv4 address on remote veth inside client namespace.
Hugo Benichie8758b52020-04-03 14:49:01 +0900791 // - configure IPv4 address on local veth inside host namespace.
792 // - add a default IPv4 /0 route sending traffic to that remote veth.
793 // - bring back one veth to the host namespace, and set it up.
794 pid_t pid = request.pid();
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900795 if (!datapath_->ConnectVethPair(pid, host_ifname, client_ifname,
796 addr_mgr_.GenerateMacAddress(),
797 client_ipv4_addr, subnet->PrefixLength(),
798 false /* enable_multicast */)) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900799 LOG(ERROR) << "ConnectNamespaceRequest: failed to create veth pair for "
800 "namespace pid "
801 << pid;
802 return;
803 }
804 if (!datapath_->ConfigureInterface(
805 host_ifname, addr_mgr_.GenerateMacAddress(), host_ipv4_addr,
806 subnet->PrefixLength(), true /* link up */,
807 false /* enable_multicast */)) {
808 LOG(ERROR) << "ConnectNamespaceRequest: cannot configure host interface "
809 << host_ifname;
810 datapath_->RemoveInterface(host_ifname);
811 return;
812 }
813 {
814 ScopedNS ns(pid);
815 if (!ns.IsValid()) {
816 LOG(ERROR) << "ConnectNamespaceRequest: cannot enter client pid " << pid;
817 datapath_->RemoveInterface(host_ifname);
818 return;
819 }
820 if (!datapath_->AddIPv4Route(host_ipv4_addr, INADDR_ANY, INADDR_ANY)) {
821 LOG(ERROR)
822 << "ConnectNamespaceRequest: failed to add default /0 route to "
823 << host_ifname << " inside namespace pid " << pid;
824 datapath_->RemoveInterface(host_ifname);
825 return;
826 }
827 }
828
829 // Host namespace routing configuration
830 // - ingress: add route to client subnet via |host_ifname|.
831 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
832 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
833 // Note that by default unsolicited ingress traffic is not forwarded to the
834 // client namespace unless the client specifically set port forwarding
835 // through permission_broker DBus APIs.
836 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
837 // both ways between client namespace and other guest containers and VMs.
838 // TODO(hugobenichi) If outbound_physical_device is defined, then set strong
839 // routing to that interface routing table.
840 if (!datapath_->AddIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
841 subnet->Netmask())) {
842 LOG(ERROR)
843 << "ConnectNamespaceRequest: failed to set route to client namespace";
844 datapath_->RemoveInterface(host_ifname);
845 return;
846 }
847 if (!datapath_->AddOutboundIPv4(host_ifname)) {
848 LOG(ERROR) << "ConnectNamespaceRequest: failed to allow FORWARD for "
849 "traffic outgoing from "
850 << host_ifname;
851 datapath_->RemoveInterface(host_ifname);
852 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
853 subnet->Netmask());
854 return;
855 }
856 if (!datapath_->AddOutboundIPv4SNATMark(host_ifname)) {
857 LOG(ERROR) << "ConnectNamespaceRequest: failed to set SNAT for traffic "
858 "outgoing from "
859 << host_ifname;
860 datapath_->RemoveInterface(host_ifname);
861 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
862 subnet->Netmask());
863 datapath_->RemoveOutboundIPv4(host_ifname);
864 return;
865 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900866
Hugo Benichi7352ad92020-04-07 16:11:59 +0900867 // Dup the client fd into our own: this guarantees that the fd number will
868 // be stable and tied to the actual kernel resources used by the client.
869 base::ScopedFD local_client_fd(dup(client_fd.get()));
870 if (!local_client_fd.is_valid()) {
871 PLOG(ERROR) << "ConnectNamespaceRequest: failed to dup() client fd";
Hugo Benichie8758b52020-04-03 14:49:01 +0900872 datapath_->RemoveInterface(host_ifname);
873 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
874 subnet->Netmask());
875 datapath_->RemoveOutboundIPv4(host_ifname);
876 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900877 return;
878 }
879
880 // Add the dupe fd to the epoll watcher.
881 // TODO(hugobenichi) Find a way to reuse base::FileDescriptorWatcher for
882 // listening to EPOLLHUP.
883 struct epoll_event epevent;
884 epevent.events = EPOLLIN; // EPOLLERR | EPOLLHUP are always waited for.
885 epevent.data.fd = local_client_fd.get();
886 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_ADD,
887 local_client_fd.get(), &epevent) != 0) {
888 PLOG(ERROR) << "ConnectNamespaceResponse: epoll_ctl(EPOLL_CTL_ADD) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900889 datapath_->RemoveInterface(host_ifname);
890 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
891 subnet->Netmask());
892 datapath_->RemoveOutboundIPv4(host_ifname);
893 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900894 return;
895 }
896
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900897 // Prepare the response before storing ConnectNamespaceInfo.
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900898 response.set_peer_ifname(client_ifname);
899 response.set_peer_ipv4_address(host_ipv4_addr);
900 response.set_host_ifname(host_ifname);
901 response.set_host_ipv4_address(client_ipv4_addr);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900902 auto* response_subnet = response.mutable_ipv4_subnet();
903 response_subnet->set_base_addr(subnet->BaseAddress());
904 response_subnet->set_prefix_len(subnet->PrefixLength());
905
906 // Store ConnectNamespaceInfo
907 connected_namespaces_next_id_++;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900908 int fdkey = local_client_fd.release();
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900909 connected_namespaces_[fdkey] = {};
910 ConnectNamespaceInfo& ns_info = connected_namespaces_[fdkey];
911 ns_info.pid = request.pid();
912 ns_info.outbound_ifname = request.outbound_physical_device();
913 ns_info.host_ifname = std::move(host_ifname);
914 ns_info.client_ifname = std::move(client_ifname);
915 ns_info.client_subnet = std::move(subnet);
916
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900917 LOG(INFO) << "Connected network namespace " << ns_info;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900918
919 if (connected_namespaces_.size() == 1) {
920 LOG(INFO) << "Starting ConnectNamespace client fds monitoring";
921 CheckConnectedNamespaces();
922 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900923}
924
925void Manager::DisconnectNamespace(int client_fd) {
926 auto it = connected_namespaces_.find(client_fd);
927 if (it == connected_namespaces_.end()) {
928 LOG(ERROR) << "No ConnectNamespaceInfo found for client_fd " << client_fd;
929 return;
930 }
931
Hugo Benichi7352ad92020-04-07 16:11:59 +0900932 // Remove the client fd dupe from the epoll watcher and close it.
933 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL, client_fd,
Hugo Benichie8758b52020-04-03 14:49:01 +0900934 nullptr) != 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900935 PLOG(ERROR) << "DisconnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900936 if (close(client_fd) < 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900937 PLOG(ERROR) << "DisconnectNamespace: close(client_fd) failed";
Hugo Benichi7352ad92020-04-07 16:11:59 +0900938
Hugo Benichie8758b52020-04-03 14:49:01 +0900939 // Destroy the interface configuration and routing configuration:
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900940 // - destroy veth pair.
Hugo Benichie8758b52020-04-03 14:49:01 +0900941 // - remove forwarding rules on host namespace.
942 // - remove SNAT marking rule on host namespace.
943 // Note that the default route set inside the client namespace by patchpanel
944 // is not destroyed: it is assumed the client will also teardown its
945 // namespace if it triggered DisconnectNamespace.
946 datapath_->RemoveInterface(it->second.host_ifname);
947 datapath_->RemoveOutboundIPv4(it->second.host_ifname);
948 datapath_->RemoveOutboundIPv4SNATMark(it->second.host_ifname);
949 datapath_->DeleteIPv4Route(it->second.client_subnet->AddressAtOffset(0),
950 it->second.client_subnet->BaseAddress(),
951 it->second.client_subnet->Netmask());
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900952
953 LOG(INFO) << "Disconnected network namespace " << it->second;
954
955 // This release the allocated IPv4 subnet.
956 connected_namespaces_.erase(it);
957}
958
Hugo Benichi7352ad92020-04-07 16:11:59 +0900959// TODO(hugobenichi) Generalize this check to all resources created by
960// patchpanel on behalf of a remote client.
961void Manager::CheckConnectedNamespaces() {
962 int max_event = 10;
963 struct epoll_event epevents[max_event];
964 int nready = epoll_wait(connected_namespaces_epollfd_, epevents, max_event,
965 0 /* do not block */);
966 if (nready < 0)
967 PLOG(ERROR) << "CheckConnectedNamespaces: epoll_wait(0) failed";
968
969 for (int i = 0; i < nready; i++)
970 if (epevents[i].events & (EPOLLHUP | EPOLLERR))
971 DisconnectNamespace(epevents[i].data.fd);
972
973 if (connected_namespaces_.empty()) {
974 LOG(INFO) << "Stopping ConnectNamespace client fds monitoring";
975 return;
976 }
977
Qijiang Fan2d7aeb42020-05-19 02:06:39 +0900978 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Hugo Benichi7352ad92020-04-07 16:11:59 +0900979 FROM_HERE,
980 base::Bind(&Manager::CheckConnectedNamespaces,
Hugo Benichie8758b52020-04-03 14:49:01 +0900981 weak_factory_.GetWeakPtr()),
Hugo Benichi7352ad92020-04-07 16:11:59 +0900982 kConnectNamespaceCheckInterval);
983}
984
Garrick Evanse94a14e2019-11-11 10:32:13 +0900985void Manager::SendGuestMessage(const GuestMessage& msg) {
Garrick Evans96e03042019-05-28 14:30:52 +0900986 IpHelperMessage ipm;
987 *ipm.mutable_guest_message() = msg;
Garrick Evans96e03042019-05-28 14:30:52 +0900988 adb_proxy_->SendMessage(ipm);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900989 mcast_proxy_->SendMessage(ipm);
990 nd_proxy_->SendMessage(ipm);
Garrick Evans96e03042019-05-28 14:30:52 +0900991}
992
Garrick Evans4ac09852020-01-16 14:09:22 +0900993void Manager::StartForwarding(const std::string& ifname_physical,
994 const std::string& ifname_virtual,
Garrick Evans4ac09852020-01-16 14:09:22 +0900995 bool ipv6,
996 bool multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +0900997 if (ifname_physical.empty() || ifname_virtual.empty())
Garrick Evans4ac09852020-01-16 14:09:22 +0900998 return;
999
1000 IpHelperMessage ipm;
1001 DeviceMessage* msg = ipm.mutable_device_message();
1002 msg->set_dev_ifname(ifname_physical);
Garrick Evans4ac09852020-01-16 14:09:22 +09001003 msg->set_br_ifname(ifname_virtual);
1004
1005 if (ipv6) {
1006 LOG(INFO) << "Starting IPv6 forwarding from " << ifname_physical << " to "
1007 << ifname_virtual;
1008
1009 if (!datapath_->AddIPv6Forwarding(ifname_physical, ifname_virtual)) {
1010 LOG(ERROR) << "Failed to setup iptables forwarding rule for IPv6 from "
1011 << ifname_physical << " to " << ifname_virtual;
1012 }
1013 if (!datapath_->MaskInterfaceFlags(ifname_physical, IFF_ALLMULTI)) {
1014 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1015 << ifname_physical;
1016 }
1017 if (!datapath_->MaskInterfaceFlags(ifname_virtual, IFF_ALLMULTI)) {
1018 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1019 << ifname_virtual;
1020 }
1021 nd_proxy_->SendMessage(ipm);
1022 }
1023
1024 if (multicast) {
1025 LOG(INFO) << "Starting multicast forwarding from " << ifname_physical
1026 << " to " << ifname_virtual;
1027 mcast_proxy_->SendMessage(ipm);
1028 }
1029}
1030
1031void Manager::StopForwarding(const std::string& ifname_physical,
1032 const std::string& ifname_virtual,
1033 bool ipv6,
1034 bool multicast) {
1035 if (ifname_physical.empty())
1036 return;
1037
1038 IpHelperMessage ipm;
1039 DeviceMessage* msg = ipm.mutable_device_message();
1040 msg->set_dev_ifname(ifname_physical);
1041 msg->set_teardown(true);
Taoyu Li7dca19a2020-03-16 16:27:07 +09001042 if (!ifname_virtual.empty()) {
1043 msg->set_br_ifname(ifname_virtual);
1044 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001045
1046 if (ipv6) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001047 if (ifname_virtual.empty()) {
1048 LOG(INFO) << "Stopping IPv6 forwarding on " << ifname_physical;
1049 } else {
1050 LOG(INFO) << "Stopping IPv6 forwarding from " << ifname_physical << " to "
1051 << ifname_virtual;
1052 datapath_->RemoveIPv6Forwarding(ifname_physical, ifname_virtual);
1053 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001054 nd_proxy_->SendMessage(ipm);
1055 }
1056
1057 if (multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001058 if (ifname_virtual.empty()) {
1059 LOG(INFO) << "Stopping multicast forwarding on " << ifname_physical;
1060 } else {
1061 LOG(INFO) << "Stopping multicast forwarding from " << ifname_physical
1062 << " to " << ifname_virtual;
1063 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001064 mcast_proxy_->SendMessage(ipm);
1065 }
1066}
1067
Garrick Evans4ac09852020-01-16 14:09:22 +09001068void Manager::OnDeviceMessageFromNDProxy(const DeviceMessage& msg) {
1069 LOG_IF(DFATAL, msg.dev_ifname().empty())
1070 << "Received DeviceMessage w/ empty dev_ifname";
1071
1072 if (!datapath_->AddIPv6HostRoute(msg.dev_ifname(), msg.guest_ip6addr(),
1073 128)) {
1074 LOG(WARNING) << "Failed to setup the IPv6 route for interface "
1075 << msg.dev_ifname();
1076 }
1077}
1078
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001079std::ostream& operator<<(std::ostream& stream,
1080 const Manager::ConnectNamespaceInfo& ns_info) {
1081 stream << "{ pid: " << ns_info.pid;
1082 if (!ns_info.outbound_ifname.empty()) {
1083 stream << ", outbound_ifname: " << ns_info.outbound_ifname;
1084 }
1085 stream << ", host_ifname: " << ns_info.host_ifname
1086 << ", client_ifname: " << ns_info.client_ifname
1087 << ", subnet: " << ns_info.client_subnet->ToCidrString() << '}';
1088 return stream;
1089}
1090
Garrick Evans3388a032020-03-24 11:25:55 +09001091} // namespace patchpanel