blob: 3721977b435c20a0cf38d11caacd9047152bef77 [file] [log] [blame]
Kevin Cernekee95d4ae92016-06-19 10:26:29 -07001// Copyright 2016 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Garrick Evans3388a032020-03-24 11:25:55 +09005#include "patchpanel/manager.h"
Kevin Cernekee4e62cc12016-12-03 11:50:53 -08006
Kevin Cernekee95d4ae92016-06-19 10:26:29 -07007#include <arpa/inet.h>
Garrick Evans4ac09852020-01-16 14:09:22 +09008#include <net/if.h>
Hugo Benichi935eca92018-07-03 13:47:24 +09009#include <netinet/in.h>
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070010#include <stdint.h>
Hugo Benichi7352ad92020-04-07 16:11:59 +090011#include <sys/epoll.h>
Garrick Evans54861622019-07-19 09:05:09 +090012#include <sys/prctl.h>
Garrick Evans96e03042019-05-28 14:30:52 +090013#include <sys/socket.h>
14#include <sys/un.h>
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070015
Kevin Cernekee27bcaa62016-12-03 11:16:26 -080016#include <utility>
17
Hugo Benichi7d9d8db2020-03-30 15:56:56 +090018#include "base/files/scoped_file.h"
Hugo Benichicc6850f2020-01-17 13:26:06 +090019#include <base/bind.h>
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070020#include <base/logging.h>
Taoyu Lic85c44b2019-12-04 17:32:57 +090021#include <base/strings/string_number_conversions.h>
Garrick Evans96e03042019-05-28 14:30:52 +090022#include <base/strings/string_split.h>
Garrick Evans6f258d02019-06-28 16:32:07 +090023#include <base/strings/string_util.h>
Taoyu Li179dcc62019-10-17 11:21:08 +090024#include <base/strings/stringprintf.h>
hschamf9546312020-04-14 15:12:40 +090025#include <base/threading/thread_task_runner_handle.h>
Taoyu Lic85c44b2019-12-04 17:32:57 +090026#include <brillo/key_value_store.h>
Kevin Cernekee27bcaa62016-12-03 11:16:26 -080027#include <brillo/minijail/minijail.h>
28
Garrick Evans3388a032020-03-24 11:25:55 +090029#include "patchpanel/ipc.pb.h"
30#include "patchpanel/mac_address_generator.h"
31#include "patchpanel/net_util.h"
32#include "patchpanel/routing_service.h"
33#include "patchpanel/scoped_ns.h"
Garrick Evans428e4762018-12-11 15:18:42 +090034
Garrick Evans3388a032020-03-24 11:25:55 +090035namespace patchpanel {
Garrick Evans08843932019-09-17 14:41:08 +090036namespace {
Garrick Evans4c042572019-12-17 13:42:25 +090037constexpr int kSubprocessRestartDelayMs = 900;
Garrick Evans08843932019-09-17 14:41:08 +090038
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +090039constexpr char kNDProxyFeatureName[] = "ARC NDProxy";
40constexpr int kNDProxyMinAndroidSdkVersion = 28; // P
41constexpr int kNDProxyMinChromeMilestone = 80;
Taoyu Lic85c44b2019-12-04 17:32:57 +090042
Garrick Evansf5862122020-03-16 09:13:45 +090043constexpr char kArcVmMultinetFeatureName[] = "ARCVM Multinet";
44constexpr int kArcVmMultinetMinAndroidSdkVersion = 29; // R DEV
45constexpr int kArcVmMultinetMinChromeMilestone = 99; // DISABLED
46
Hugo Benichi7352ad92020-04-07 16:11:59 +090047// Time interval between epoll checks on file descriptors committed by callers
48// of ConnectNamespace DBus API.
49constexpr const base::TimeDelta kConnectNamespaceCheckInterval =
50 base::TimeDelta::FromSeconds(30);
51
Garrick Evans08843932019-09-17 14:41:08 +090052// Passes |method_call| to |handler| and passes the response to
53// |response_sender|. If |handler| returns nullptr, an empty response is
54// created and sent.
55void HandleSynchronousDBusMethodCall(
56 base::Callback<std::unique_ptr<dbus::Response>(dbus::MethodCall*)> handler,
57 dbus::MethodCall* method_call,
58 dbus::ExportedObject::ResponseSender response_sender) {
59 std::unique_ptr<dbus::Response> response = handler.Run(method_call);
60 if (!response)
61 response = dbus::Response::FromMethodCall(method_call);
62 response_sender.Run(std::move(response));
63}
64
65} // namespace
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070066
Taoyu Lice7caa62019-10-01 15:43:33 +090067Manager::Manager(std::unique_ptr<HelperProcess> adb_proxy,
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090068 std::unique_ptr<HelperProcess> mcast_proxy,
Garrick Evans1f5a3612019-11-08 12:59:03 +090069 std::unique_ptr<HelperProcess> nd_proxy)
Garrick Evans3915af32019-07-25 15:44:34 +090070 : adb_proxy_(std::move(adb_proxy)),
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090071 mcast_proxy_(std::move(mcast_proxy)),
Garrick Evans4ee5ce22020-03-18 07:05:17 +090072 nd_proxy_(std::move(nd_proxy)) {
Taoyu Li179dcc62019-10-17 11:21:08 +090073 runner_ = std::make_unique<MinijailedProcessRunner>();
74 datapath_ = std::make_unique<Datapath>(runner_.get());
Hugo Benichi7352ad92020-04-07 16:11:59 +090075 connected_namespaces_epollfd_ = epoll_create(1 /* size */);
Taoyu Li179dcc62019-10-17 11:21:08 +090076}
Long Chengd4415582019-09-24 19:16:09 +000077
Garrick Evans207e7482019-12-16 11:54:36 +090078Manager::~Manager() {
79 OnShutdown(nullptr);
80}
81
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +090082std::map<const std::string, bool> Manager::cached_feature_enabled_ = {};
83
84bool Manager::ShouldEnableFeature(
85 int min_android_sdk_version,
86 int min_chrome_milestone,
87 const std::vector<std::string>& supported_boards,
88 const std::string& feature_name) {
89 static const char kLsbReleasePath[] = "/etc/lsb-release";
90
91 const auto& cached_result = cached_feature_enabled_.find(feature_name);
92 if (cached_result != cached_feature_enabled_.end())
93 return cached_result->second;
94
95 auto check = [min_android_sdk_version, min_chrome_milestone,
96 &supported_boards, &feature_name]() {
97 brillo::KeyValueStore store;
98 if (!store.Load(base::FilePath(kLsbReleasePath))) {
99 LOG(ERROR) << "Could not read lsb-release";
100 return false;
101 }
102
103 std::string value;
104 if (!store.GetString("CHROMEOS_ARC_ANDROID_SDK_VERSION", &value)) {
105 LOG(ERROR) << feature_name
106 << " disabled - cannot determine Android SDK version";
107 return false;
108 }
109 int ver = 0;
110 if (!base::StringToInt(value.c_str(), &ver)) {
111 LOG(ERROR) << feature_name << " disabled - invalid Android SDK version";
112 return false;
113 }
114 if (ver < min_android_sdk_version) {
115 LOG(INFO) << feature_name << " disabled for Android SDK " << value;
116 return false;
117 }
118
119 if (!store.GetString("CHROMEOS_RELEASE_CHROME_MILESTONE", &value)) {
120 LOG(ERROR) << feature_name
121 << " disabled - cannot determine ChromeOS milestone";
122 return false;
123 }
124 if (!base::StringToInt(value.c_str(), &ver)) {
125 LOG(ERROR) << feature_name << " disabled - invalid ChromeOS milestone";
126 return false;
127 }
128 if (ver < min_chrome_milestone) {
129 LOG(INFO) << feature_name << " disabled for ChromeOS milestone " << value;
130 return false;
131 }
132
133 if (!store.GetString("CHROMEOS_RELEASE_BOARD", &value)) {
134 LOG(ERROR) << feature_name << " disabled - cannot determine board";
135 return false;
136 }
137 if (!supported_boards.empty() &&
138 std::find(supported_boards.begin(), supported_boards.end(), value) ==
139 supported_boards.end()) {
140 LOG(INFO) << feature_name << " disabled for board " << value;
141 return false;
142 }
143 return true;
144 };
145
146 bool result = check();
147 cached_feature_enabled_.emplace(feature_name, result);
148 return result;
149}
150
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700151int Manager::OnInit() {
Garrick Evans54861622019-07-19 09:05:09 +0900152 prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800153
154 // Handle subprocess lifecycle.
155 process_reaper_.Register(this);
Hugo Benichi935eca92018-07-03 13:47:24 +0900156
157 CHECK(process_reaper_.WatchForChild(
Garrick Evans96e03042019-05-28 14:30:52 +0900158 FROM_HERE, adb_proxy_->pid(),
159 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
160 adb_proxy_->pid())))
161 << "Failed to watch adb-proxy child process";
Taoyu Liaf944c92019-10-01 12:22:31 +0900162 CHECK(process_reaper_.WatchForChild(
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900163 FROM_HERE, mcast_proxy_->pid(),
164 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
165 nd_proxy_->pid())))
166 << "Failed to watch multicast-proxy child process";
167 CHECK(process_reaper_.WatchForChild(
Taoyu Liaf944c92019-10-01 12:22:31 +0900168 FROM_HERE, nd_proxy_->pid(),
169 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
170 nd_proxy_->pid())))
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900171 << "Failed to watch nd-proxy child process";
Garrick Evans96e03042019-05-28 14:30:52 +0900172
Garrick Evans49879532018-12-03 13:15:36 +0900173 // Run after Daemon::OnInit().
hschamf9546312020-04-14 15:12:40 +0900174 base::ThreadTaskRunnerHandle::Get()->PostTask(
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700175 FROM_HERE,
176 base::Bind(&Manager::InitialSetup, weak_factory_.GetWeakPtr()));
177
178 return DBusDaemon::OnInit();
179}
180
181void Manager::InitialSetup() {
Garrick Evans08843932019-09-17 14:41:08 +0900182 LOG(INFO) << "Setting up DBus service interface";
183 dbus_svc_path_ = bus_->GetExportedObject(
184 dbus::ObjectPath(patchpanel::kPatchPanelServicePath));
185 if (!dbus_svc_path_) {
186 LOG(FATAL) << "Failed to export " << patchpanel::kPatchPanelServicePath
187 << " object";
188 }
189
190 using ServiceMethod =
191 std::unique_ptr<dbus::Response> (Manager::*)(dbus::MethodCall*);
192 const std::map<const char*, ServiceMethod> kServiceMethods = {
193 {patchpanel::kArcStartupMethod, &Manager::OnArcStartup},
194 {patchpanel::kArcShutdownMethod, &Manager::OnArcShutdown},
195 {patchpanel::kArcVmStartupMethod, &Manager::OnArcVmStartup},
196 {patchpanel::kArcVmShutdownMethod, &Manager::OnArcVmShutdown},
Garrick Evans47c19272019-11-21 10:58:21 +0900197 {patchpanel::kTerminaVmStartupMethod, &Manager::OnTerminaVmStartup},
198 {patchpanel::kTerminaVmShutdownMethod, &Manager::OnTerminaVmShutdown},
Garrick Evans51d5b552020-01-30 10:42:06 +0900199 {patchpanel::kPluginVmStartupMethod, &Manager::OnPluginVmStartup},
200 {patchpanel::kPluginVmShutdownMethod, &Manager::OnPluginVmShutdown},
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900201 {patchpanel::kSetVpnIntentMethod, &Manager::OnSetVpnIntent},
Hugo Benichib56b77c2020-01-15 16:00:56 +0900202 {patchpanel::kConnectNamespaceMethod, &Manager::OnConnectNamespace},
Garrick Evans08843932019-09-17 14:41:08 +0900203 };
204
205 for (const auto& kv : kServiceMethods) {
206 if (!dbus_svc_path_->ExportMethodAndBlock(
207 patchpanel::kPatchPanelInterface, kv.first,
208 base::Bind(&HandleSynchronousDBusMethodCall,
209 base::Bind(kv.second, base::Unretained(this))))) {
210 LOG(FATAL) << "Failed to export method " << kv.first;
211 }
212 }
213
214 if (!bus_->RequestOwnershipAndBlock(patchpanel::kPatchPanelServiceName,
215 dbus::Bus::REQUIRE_PRIMARY)) {
216 LOG(FATAL) << "Failed to take ownership of "
217 << patchpanel::kPatchPanelServiceName;
218 }
219 LOG(INFO) << "DBus service interface ready";
220
Taoyu Li6d479442019-12-09 13:02:29 +0900221 auto& runner = datapath_->runner();
Garrick Evans7cf8c542020-05-25 09:50:17 +0900222 // Enable IPv4 packet forwarding
223 if (runner.sysctl_w("net.ipv4.ip_forward", "1") != 0) {
224 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
225 << " Guest connectivity will not work correctly.";
226 }
Garrick Evans28d194e2019-12-17 10:22:28 +0900227 // Limit local port range: Android owns 47104-61000.
228 // TODO(garrick): The original history behind this tweak is gone. Some
229 // investigation is needed to see if it is still applicable.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900230 if (runner.sysctl_w("net.ipv4.ip_local_port_range", "32768 47103") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900231 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
232 << " apps may not work correctly.";
233 }
Taoyu Li6d479442019-12-09 13:02:29 +0900234 // Enable IPv6 packet forarding
Garrick Evans8e8e3472020-01-23 14:03:50 +0900235 if (runner.sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0) {
Taoyu Li6d479442019-12-09 13:02:29 +0900236 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
237 << " IPv6 functionality may be broken.";
238 }
239 // Kernel proxy_ndp is only needed for legacy IPv6 configuration
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +0900240 if (!ShouldEnableFeature(kNDProxyMinAndroidSdkVersion,
Garrick Evansf5862122020-03-16 09:13:45 +0900241 kNDProxyMinChromeMilestone, {},
242 kNDProxyFeatureName) &&
Garrick Evans8e8e3472020-01-23 14:03:50 +0900243 runner.sysctl_w("net.ipv6.conf.all.proxy_ndp", "1") != 0) {
Taoyu Li6d479442019-12-09 13:02:29 +0900244 LOG(ERROR) << "Failed to update net.ipv6.conf.all.proxy_ndp."
245 << " IPv6 functionality may be broken.";
246 }
247
Garrick Evansd291af62020-05-25 10:39:06 +0900248 if (!datapath_->AddSNATMarkRules()) {
249 LOG(ERROR) << "Failed to install SNAT mark rules."
250 << " Guest connectivity may be broken.";
251 }
252 if (!datapath_->AddForwardEstablishedRule()) {
253 LOG(ERROR) << "Failed to install forwarding rule for established"
254 << " connections.";
255 }
256
Garrick Evansff6e37f2020-05-25 10:54:47 +0900257 // TODO(chromium:898210): Move interface-specific masquerading setup to shill;
258 // such that we can better set up the masquerade rules based on connection
259 // type rather than interface names.
260 if (!datapath_->AddInterfaceSNAT("wwan+")) {
261 LOG(ERROR) << "Failed to set up wifi masquerade";
262 }
263
Garrick Evansc50426b2020-05-25 11:00:55 +0900264 if (!datapath_->AddOutboundIPv4SNATMark("vmtap+")) {
265 LOG(ERROR) << "Failed to set up NAT for TAP devices."
266 << " Guest connectivity may be broken.";
267 }
268
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900269 routing_svc_ = std::make_unique<RoutingService>();
270
Garrick Evans4ac09852020-01-16 14:09:22 +0900271 nd_proxy_->RegisterDeviceMessageHandler(base::Bind(
272 &Manager::OnDeviceMessageFromNDProxy, weak_factory_.GetWeakPtr()));
273
Garrick Evans69b85872020-02-04 11:40:26 +0900274 shill_client_ = std::make_unique<ShillClient>(bus_);
Garrick Evans1b1f67c2020-02-04 16:21:25 +0900275 auto* const forwarder = static_cast<TrafficForwarder*>(this);
Garrick Evans5d55f5e2019-07-17 15:28:10 +0900276
Garrick Evansf5862122020-03-16 09:13:45 +0900277 arc_svc_ = std::make_unique<ArcService>(
278 shill_client_.get(), datapath_.get(), &addr_mgr_, forwarder,
279 ShouldEnableFeature(kArcVmMultinetMinAndroidSdkVersion,
280 kArcVmMultinetMinChromeMilestone, {},
281 kArcVmMultinetFeatureName));
Garrick Evans1b1f67c2020-02-04 16:21:25 +0900282 cros_svc_ = std::make_unique<CrostiniService>(shill_client_.get(), &addr_mgr_,
283 datapath_.get(), forwarder);
Taoyu Liaf944c92019-10-01 12:22:31 +0900284
285 nd_proxy_->Listen();
Long Chengd4415582019-09-24 19:16:09 +0000286}
Garrick Evans49879532018-12-03 13:15:36 +0900287
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800288void Manager::OnShutdown(int* exit_code) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900289 LOG(INFO) << "Shutting down and cleaning up";
Garrick Evans207e7482019-12-16 11:54:36 +0900290 cros_svc_.reset();
291 arc_svc_.reset();
Hugo Benichi7352ad92020-04-07 16:11:59 +0900292 close(connected_namespaces_epollfd_);
Hugo Benichie8758b52020-04-03 14:49:01 +0900293 // Tear down any remaining connected namespace.
294 std::vector<int> connected_namespaces_fdkeys;
295 for (const auto& kv : connected_namespaces_)
296 connected_namespaces_fdkeys.push_back(kv.first);
297 for (const int fdkey : connected_namespaces_fdkeys)
298 DisconnectNamespace(fdkey);
Garrick Evans28d194e2019-12-17 10:22:28 +0900299
Garrick Evansc50426b2020-05-25 11:00:55 +0900300 datapath_->RemoveOutboundIPv4SNATMark("vmtap+");
Garrick Evansff6e37f2020-05-25 10:54:47 +0900301 datapath_->RemoveInterfaceSNAT("wwan+");
Garrick Evansd291af62020-05-25 10:39:06 +0900302 datapath_->RemoveForwardEstablishedRule();
303 datapath_->RemoveSNATMarkRules();
304
Garrick Evans7cf8c542020-05-25 09:50:17 +0900305 auto& runner = datapath_->runner();
Garrick Evans28d194e2019-12-17 10:22:28 +0900306 // Restore original local port range.
307 // TODO(garrick): The original history behind this tweak is gone. Some
308 // investigation is needed to see if it is still applicable.
Garrick Evans7cf8c542020-05-25 09:50:17 +0900309 if (runner.sysctl_w("net.ipv4.ip_local_port_range", "32768 61000") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900310 LOG(ERROR) << "Failed to restore local port range";
311 }
Garrick Evans7cf8c542020-05-25 09:50:17 +0900312 // Disable packet forwarding
313 if (runner.sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0) {
314 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
315 }
316 if (runner.sysctl_w("net.ipv4.ip_forward", "0") != 0) {
317 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
318 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800319}
320
Garrick Evans4c042572019-12-17 13:42:25 +0900321void Manager::OnSubprocessExited(pid_t pid, const siginfo_t&) {
322 LOG(ERROR) << "Subprocess " << pid << " exited unexpectedly -"
323 << " attempting to restart";
324
325 HelperProcess* proc;
326 if (pid == adb_proxy_->pid()) {
327 proc = adb_proxy_.get();
328 } else if (pid == mcast_proxy_->pid()) {
329 proc = mcast_proxy_.get();
330 } else if (pid == nd_proxy_->pid()) {
331 proc = nd_proxy_.get();
332 } else {
333 LOG(DFATAL) << "Unknown child process";
334 return;
335 }
336
337 process_reaper_.ForgetChild(pid);
338
hschamf9546312020-04-14 15:12:40 +0900339 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Garrick Evans4c042572019-12-17 13:42:25 +0900340 FROM_HERE,
341 base::Bind(&Manager::RestartSubprocess, weak_factory_.GetWeakPtr(), proc),
342 base::TimeDelta::FromMilliseconds((2 << proc->restarts()) *
343 kSubprocessRestartDelayMs));
344}
345
346void Manager::RestartSubprocess(HelperProcess* subproc) {
347 if (subproc->Restart()) {
348 DCHECK(process_reaper_.WatchForChild(
349 FROM_HERE, subproc->pid(),
350 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
351 subproc->pid())))
352 << "Failed to watch child process " << subproc->pid();
353 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800354}
355
Garrick Evanse94a14e2019-11-11 10:32:13 +0900356bool Manager::StartArc(pid_t pid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900357 if (!arc_svc_->Start(pid))
358 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900359
360 GuestMessage msg;
361 msg.set_event(GuestMessage::START);
362 msg.set_type(GuestMessage::ARC);
363 msg.set_arc_pid(pid);
364 SendGuestMessage(msg);
365
366 return true;
367}
368
Garrick Evans21173b12019-11-20 15:23:16 +0900369void Manager::StopArc(pid_t pid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900370 GuestMessage msg;
371 msg.set_event(GuestMessage::STOP);
372 msg.set_type(GuestMessage::ARC);
373 SendGuestMessage(msg);
374
Garrick Evans21173b12019-11-20 15:23:16 +0900375 arc_svc_->Stop(pid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900376}
377
Garrick Evans015b0d62020-02-07 09:06:38 +0900378bool Manager::StartArcVm(uint32_t cid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900379 if (!arc_svc_->Start(cid))
380 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900381
382 GuestMessage msg;
383 msg.set_event(GuestMessage::START);
384 msg.set_type(GuestMessage::ARC_VM);
385 msg.set_arcvm_vsock_cid(cid);
386 SendGuestMessage(msg);
387
388 return true;
389}
390
Garrick Evans015b0d62020-02-07 09:06:38 +0900391void Manager::StopArcVm(uint32_t cid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900392 GuestMessage msg;
393 msg.set_event(GuestMessage::STOP);
394 msg.set_type(GuestMessage::ARC_VM);
395 SendGuestMessage(msg);
396
Garrick Evans21173b12019-11-20 15:23:16 +0900397 arc_svc_->Stop(cid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900398}
399
Garrick Evans51d5b552020-01-30 10:42:06 +0900400bool Manager::StartCrosVm(uint64_t vm_id,
401 GuestMessage::GuestType vm_type,
Garrick Evans53a2a982020-02-05 10:53:35 +0900402 uint32_t subnet_index) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900403 DCHECK(vm_type == GuestMessage::TERMINA_VM ||
404 vm_type == GuestMessage::PLUGIN_VM);
405
406 if (!cros_svc_->Start(vm_id, vm_type == GuestMessage::TERMINA_VM,
407 subnet_index))
Garrick Evans47c19272019-11-21 10:58:21 +0900408 return false;
409
410 GuestMessage msg;
411 msg.set_event(GuestMessage::START);
Garrick Evans51d5b552020-01-30 10:42:06 +0900412 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900413 SendGuestMessage(msg);
414
415 return true;
416}
417
Garrick Evans51d5b552020-01-30 10:42:06 +0900418void Manager::StopCrosVm(uint64_t vm_id, GuestMessage::GuestType vm_type) {
Garrick Evans47c19272019-11-21 10:58:21 +0900419 GuestMessage msg;
420 msg.set_event(GuestMessage::STOP);
Garrick Evans51d5b552020-01-30 10:42:06 +0900421 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900422 SendGuestMessage(msg);
423
Garrick Evans51d5b552020-01-30 10:42:06 +0900424 cros_svc_->Stop(vm_id, vm_type == GuestMessage::TERMINA_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900425}
426
Garrick Evans08843932019-09-17 14:41:08 +0900427std::unique_ptr<dbus::Response> Manager::OnArcStartup(
428 dbus::MethodCall* method_call) {
429 LOG(INFO) << "ARC++ starting up";
430
431 std::unique_ptr<dbus::Response> dbus_response(
432 dbus::Response::FromMethodCall(method_call));
433
434 dbus::MessageReader reader(method_call);
435 dbus::MessageWriter writer(dbus_response.get());
436
437 patchpanel::ArcStartupRequest request;
438 patchpanel::ArcStartupResponse response;
439
440 if (!reader.PopArrayOfBytesAsProto(&request)) {
441 LOG(ERROR) << "Unable to parse request";
442 writer.AppendProtoAsArrayOfBytes(response);
443 return dbus_response;
444 }
445
Garrick Evanse01bf072019-11-15 09:08:19 +0900446 if (!StartArc(request.pid()))
447 LOG(ERROR) << "Failed to start ARC++ network service";
Garrick Evanse94a14e2019-11-11 10:32:13 +0900448
Garrick Evans08843932019-09-17 14:41:08 +0900449 writer.AppendProtoAsArrayOfBytes(response);
450 return dbus_response;
451}
452
453std::unique_ptr<dbus::Response> Manager::OnArcShutdown(
454 dbus::MethodCall* method_call) {
455 LOG(INFO) << "ARC++ shutting down";
456
457 std::unique_ptr<dbus::Response> dbus_response(
458 dbus::Response::FromMethodCall(method_call));
459
460 dbus::MessageReader reader(method_call);
461 dbus::MessageWriter writer(dbus_response.get());
462
463 patchpanel::ArcShutdownRequest request;
464 patchpanel::ArcShutdownResponse response;
465
466 if (!reader.PopArrayOfBytesAsProto(&request)) {
467 LOG(ERROR) << "Unable to parse request";
468 writer.AppendProtoAsArrayOfBytes(response);
469 return dbus_response;
470 }
471
Garrick Evans21173b12019-11-20 15:23:16 +0900472 StopArc(request.pid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900473
Garrick Evans08843932019-09-17 14:41:08 +0900474 writer.AppendProtoAsArrayOfBytes(response);
475 return dbus_response;
476}
477
478std::unique_ptr<dbus::Response> Manager::OnArcVmStartup(
479 dbus::MethodCall* method_call) {
480 LOG(INFO) << "ARCVM starting up";
481
482 std::unique_ptr<dbus::Response> dbus_response(
483 dbus::Response::FromMethodCall(method_call));
484
485 dbus::MessageReader reader(method_call);
486 dbus::MessageWriter writer(dbus_response.get());
487
488 patchpanel::ArcVmStartupRequest request;
489 patchpanel::ArcVmStartupResponse response;
490
491 if (!reader.PopArrayOfBytesAsProto(&request)) {
492 LOG(ERROR) << "Unable to parse request";
493 writer.AppendProtoAsArrayOfBytes(response);
494 return dbus_response;
495 }
496
Garrick Evans47c19272019-11-21 10:58:21 +0900497 if (!StartArcVm(request.cid())) {
Garrick Evanse01bf072019-11-15 09:08:19 +0900498 LOG(ERROR) << "Failed to start ARCVM network service";
Garrick Evans47c19272019-11-21 10:58:21 +0900499 writer.AppendProtoAsArrayOfBytes(response);
500 return dbus_response;
Garrick Evanse01bf072019-11-15 09:08:19 +0900501 }
Garrick Evanse94a14e2019-11-11 10:32:13 +0900502
Garrick Evans47c19272019-11-21 10:58:21 +0900503 // Populate the response with the known devices.
Garrick Evans38b25a42020-04-06 15:17:42 +0900504 for (const auto* config : arc_svc_->GetDeviceConfigs()) {
505 if (config->tap_ifname().empty())
506 continue;
Garrick Evans47c19272019-11-21 10:58:21 +0900507
Garrick Evans38b25a42020-04-06 15:17:42 +0900508 auto* dev = response.add_devices();
509 dev->set_ifname(config->tap_ifname());
510 dev->set_ipv4_addr(config->guest_ipv4_addr());
511 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900512
Garrick Evans08843932019-09-17 14:41:08 +0900513 writer.AppendProtoAsArrayOfBytes(response);
514 return dbus_response;
515}
516
517std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
518 dbus::MethodCall* method_call) {
519 LOG(INFO) << "ARCVM shutting down";
520
521 std::unique_ptr<dbus::Response> dbus_response(
522 dbus::Response::FromMethodCall(method_call));
523
524 dbus::MessageReader reader(method_call);
525 dbus::MessageWriter writer(dbus_response.get());
526
527 patchpanel::ArcVmShutdownRequest request;
528 patchpanel::ArcVmShutdownResponse response;
529
530 if (!reader.PopArrayOfBytesAsProto(&request)) {
531 LOG(ERROR) << "Unable to parse request";
532 writer.AppendProtoAsArrayOfBytes(response);
533 return dbus_response;
534 }
535
Garrick Evans21173b12019-11-20 15:23:16 +0900536 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900537
Garrick Evans08843932019-09-17 14:41:08 +0900538 writer.AppendProtoAsArrayOfBytes(response);
539 return dbus_response;
540}
541
Garrick Evans47c19272019-11-21 10:58:21 +0900542std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
543 dbus::MethodCall* method_call) {
544 LOG(INFO) << "Termina VM starting up";
545
546 std::unique_ptr<dbus::Response> dbus_response(
547 dbus::Response::FromMethodCall(method_call));
548
549 dbus::MessageReader reader(method_call);
550 dbus::MessageWriter writer(dbus_response.get());
551
552 patchpanel::TerminaVmStartupRequest request;
553 patchpanel::TerminaVmStartupResponse response;
554
555 if (!reader.PopArrayOfBytesAsProto(&request)) {
556 LOG(ERROR) << "Unable to parse request";
557 writer.AppendProtoAsArrayOfBytes(response);
558 return dbus_response;
559 }
560
561 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900562 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900563 LOG(ERROR) << "Failed to start Termina VM network service";
564 writer.AppendProtoAsArrayOfBytes(response);
565 return dbus_response;
566 }
567
Garrick Evans51d5b552020-01-30 10:42:06 +0900568 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900569 if (!tap) {
570 LOG(DFATAL) << "TAP device missing";
571 writer.AppendProtoAsArrayOfBytes(response);
572 return dbus_response;
573 }
Garrick Evans47c19272019-11-21 10:58:21 +0900574
Garrick Evansb1c93712020-01-22 09:28:25 +0900575 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900576 dev->set_ifname(tap->host_ifname());
577 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900578 if (!subnet) {
579 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
580 writer.AppendProtoAsArrayOfBytes(response);
581 return dbus_response;
582 }
583 auto* resp_subnet = dev->mutable_ipv4_subnet();
584 resp_subnet->set_base_addr(subnet->BaseAddress());
585 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900586 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900587 if (!subnet) {
588 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
589 writer.AppendProtoAsArrayOfBytes(response);
590 return dbus_response;
591 }
592 resp_subnet = response.mutable_container_subnet();
593 resp_subnet->set_base_addr(subnet->BaseAddress());
594 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900595
596 writer.AppendProtoAsArrayOfBytes(response);
597 return dbus_response;
598}
599
600std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
601 dbus::MethodCall* method_call) {
602 LOG(INFO) << "Termina VM shutting down";
603
604 std::unique_ptr<dbus::Response> dbus_response(
605 dbus::Response::FromMethodCall(method_call));
606
607 dbus::MessageReader reader(method_call);
608 dbus::MessageWriter writer(dbus_response.get());
609
610 patchpanel::TerminaVmShutdownRequest request;
611 patchpanel::TerminaVmShutdownResponse response;
612
613 if (!reader.PopArrayOfBytesAsProto(&request)) {
614 LOG(ERROR) << "Unable to parse request";
615 writer.AppendProtoAsArrayOfBytes(response);
616 return dbus_response;
617 }
618
Garrick Evans51d5b552020-01-30 10:42:06 +0900619 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
620
621 writer.AppendProtoAsArrayOfBytes(response);
622 return dbus_response;
623}
624
625std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
626 dbus::MethodCall* method_call) {
627 LOG(INFO) << "Plugin VM starting up";
628
629 std::unique_ptr<dbus::Response> dbus_response(
630 dbus::Response::FromMethodCall(method_call));
631
632 dbus::MessageReader reader(method_call);
633 dbus::MessageWriter writer(dbus_response.get());
634
635 patchpanel::PluginVmStartupRequest request;
636 patchpanel::PluginVmStartupResponse response;
637
638 if (!reader.PopArrayOfBytesAsProto(&request)) {
639 LOG(ERROR) << "Unable to parse request";
640 writer.AppendProtoAsArrayOfBytes(response);
641 return dbus_response;
642 }
643
Garrick Evans08fb34b2020-02-20 10:50:17 +0900644 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900645 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900646 LOG(ERROR) << "Failed to start Plugin VM network service";
647 writer.AppendProtoAsArrayOfBytes(response);
648 return dbus_response;
649 }
650
651 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
652 if (!tap) {
653 LOG(DFATAL) << "TAP device missing";
654 writer.AppendProtoAsArrayOfBytes(response);
655 return dbus_response;
656 }
657
Garrick Evans51d5b552020-01-30 10:42:06 +0900658 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900659 dev->set_ifname(tap->host_ifname());
660 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900661 if (!subnet) {
662 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
663 writer.AppendProtoAsArrayOfBytes(response);
664 return dbus_response;
665 }
666 auto* resp_subnet = dev->mutable_ipv4_subnet();
667 resp_subnet->set_base_addr(subnet->BaseAddress());
668 resp_subnet->set_prefix_len(subnet->PrefixLength());
669
670 writer.AppendProtoAsArrayOfBytes(response);
671 return dbus_response;
672}
673
674std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
675 dbus::MethodCall* method_call) {
676 LOG(INFO) << "Plugin VM shutting down";
677
678 std::unique_ptr<dbus::Response> dbus_response(
679 dbus::Response::FromMethodCall(method_call));
680
681 dbus::MessageReader reader(method_call);
682 dbus::MessageWriter writer(dbus_response.get());
683
684 patchpanel::PluginVmShutdownRequest request;
685 patchpanel::PluginVmShutdownResponse response;
686
687 if (!reader.PopArrayOfBytesAsProto(&request)) {
688 LOG(ERROR) << "Unable to parse request";
689 writer.AppendProtoAsArrayOfBytes(response);
690 return dbus_response;
691 }
692
693 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900694
695 writer.AppendProtoAsArrayOfBytes(response);
696 return dbus_response;
697}
698
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900699std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
700 dbus::MethodCall* method_call) {
701 std::unique_ptr<dbus::Response> dbus_response(
702 dbus::Response::FromMethodCall(method_call));
703
704 dbus::MessageReader reader(method_call);
705 dbus::MessageWriter writer(dbus_response.get());
706
707 patchpanel::SetVpnIntentRequest request;
708 patchpanel::SetVpnIntentResponse response;
709
710 bool success = reader.PopArrayOfBytesAsProto(&request);
711 if (!success) {
712 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
713 // Do not return yet to make sure we close the received fd.
714 }
715
716 base::ScopedFD client_socket;
717 reader.PopFileDescriptor(&client_socket);
718
719 if (success)
720 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
721
722 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900723
724 writer.AppendProtoAsArrayOfBytes(response);
725 return dbus_response;
726}
727
728std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
729 dbus::MethodCall* method_call) {
730 std::unique_ptr<dbus::Response> dbus_response(
731 dbus::Response::FromMethodCall(method_call));
732
733 dbus::MessageReader reader(method_call);
734 dbus::MessageWriter writer(dbus_response.get());
735
736 patchpanel::ConnectNamespaceRequest request;
737 patchpanel::ConnectNamespaceResponse response;
738
Hugo Benichicc6850f2020-01-17 13:26:06 +0900739 bool success = true;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900740 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900741 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
742 // Do not return yet to make sure we close the received fd and
743 // validate other arguments.
744 success = false;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900745 }
746
Hugo Benichicc6850f2020-01-17 13:26:06 +0900747 base::ScopedFD client_fd;
748 reader.PopFileDescriptor(&client_fd);
749 if (!client_fd.is_valid()) {
750 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
751 success = false;
752 }
753
754 pid_t pid = request.pid();
755 {
756 ScopedNS ns(pid);
757 if (!ns.IsValid()) {
758 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
759 success = false;
760 }
761 }
762
763 const std::string& outbound_ifname = request.outbound_physical_device();
764 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
765 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
766 << outbound_ifname;
767 success = false;
768 }
769
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900770 if (success)
771 ConnectNamespace(std::move(client_fd), request, response);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900772
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900773 writer.AppendProtoAsArrayOfBytes(response);
774 return dbus_response;
775}
776
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900777void Manager::ConnectNamespace(
778 base::ScopedFD client_fd,
779 const patchpanel::ConnectNamespaceRequest& request,
780 patchpanel::ConnectNamespaceResponse& response) {
781 std::unique_ptr<Subnet> subnet =
782 addr_mgr_.AllocateIPv4Subnet(AddressManager::Guest::MINIJAIL_NETNS);
783 if (!subnet) {
784 LOG(ERROR) << "ConnectNamespaceRequest: exhausted IPv4 subnet space";
785 return;
786 }
787
788 const std::string ifname_id = std::to_string(connected_namespaces_next_id_);
789 const std::string host_ifname = "arc_ns" + ifname_id;
790 const std::string client_ifname = "veth" + ifname_id;
Hugo Benichie8758b52020-04-03 14:49:01 +0900791 const uint32_t host_ipv4_addr = subnet->AddressAtOffset(0);
792 const uint32_t client_ipv4_addr = subnet->AddressAtOffset(1);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900793
Hugo Benichie8758b52020-04-03 14:49:01 +0900794 // Veth interface configuration and client routing configuration:
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900795 // - create veth pair inside client namespace.
796 // - configure IPv4 address on remote veth inside client namespace.
Hugo Benichie8758b52020-04-03 14:49:01 +0900797 // - configure IPv4 address on local veth inside host namespace.
798 // - add a default IPv4 /0 route sending traffic to that remote veth.
799 // - bring back one veth to the host namespace, and set it up.
800 pid_t pid = request.pid();
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900801 if (!datapath_->ConnectVethPair(pid, host_ifname, client_ifname,
802 addr_mgr_.GenerateMacAddress(),
803 client_ipv4_addr, subnet->PrefixLength(),
804 false /* enable_multicast */)) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900805 LOG(ERROR) << "ConnectNamespaceRequest: failed to create veth pair for "
806 "namespace pid "
807 << pid;
808 return;
809 }
810 if (!datapath_->ConfigureInterface(
811 host_ifname, addr_mgr_.GenerateMacAddress(), host_ipv4_addr,
812 subnet->PrefixLength(), true /* link up */,
813 false /* enable_multicast */)) {
814 LOG(ERROR) << "ConnectNamespaceRequest: cannot configure host interface "
815 << host_ifname;
816 datapath_->RemoveInterface(host_ifname);
817 return;
818 }
819 {
820 ScopedNS ns(pid);
821 if (!ns.IsValid()) {
822 LOG(ERROR) << "ConnectNamespaceRequest: cannot enter client pid " << pid;
823 datapath_->RemoveInterface(host_ifname);
824 return;
825 }
826 if (!datapath_->AddIPv4Route(host_ipv4_addr, INADDR_ANY, INADDR_ANY)) {
827 LOG(ERROR)
828 << "ConnectNamespaceRequest: failed to add default /0 route to "
829 << host_ifname << " inside namespace pid " << pid;
830 datapath_->RemoveInterface(host_ifname);
831 return;
832 }
833 }
834
835 // Host namespace routing configuration
836 // - ingress: add route to client subnet via |host_ifname|.
837 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
838 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
839 // Note that by default unsolicited ingress traffic is not forwarded to the
840 // client namespace unless the client specifically set port forwarding
841 // through permission_broker DBus APIs.
842 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
843 // both ways between client namespace and other guest containers and VMs.
844 // TODO(hugobenichi) If outbound_physical_device is defined, then set strong
845 // routing to that interface routing table.
846 if (!datapath_->AddIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
847 subnet->Netmask())) {
848 LOG(ERROR)
849 << "ConnectNamespaceRequest: failed to set route to client namespace";
850 datapath_->RemoveInterface(host_ifname);
851 return;
852 }
853 if (!datapath_->AddOutboundIPv4(host_ifname)) {
854 LOG(ERROR) << "ConnectNamespaceRequest: failed to allow FORWARD for "
855 "traffic outgoing from "
856 << host_ifname;
857 datapath_->RemoveInterface(host_ifname);
858 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
859 subnet->Netmask());
860 return;
861 }
862 if (!datapath_->AddOutboundIPv4SNATMark(host_ifname)) {
863 LOG(ERROR) << "ConnectNamespaceRequest: failed to set SNAT for traffic "
864 "outgoing from "
865 << host_ifname;
866 datapath_->RemoveInterface(host_ifname);
867 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
868 subnet->Netmask());
869 datapath_->RemoveOutboundIPv4(host_ifname);
870 return;
871 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900872
Hugo Benichi7352ad92020-04-07 16:11:59 +0900873 // Dup the client fd into our own: this guarantees that the fd number will
874 // be stable and tied to the actual kernel resources used by the client.
875 base::ScopedFD local_client_fd(dup(client_fd.get()));
876 if (!local_client_fd.is_valid()) {
877 PLOG(ERROR) << "ConnectNamespaceRequest: failed to dup() client fd";
Hugo Benichie8758b52020-04-03 14:49:01 +0900878 datapath_->RemoveInterface(host_ifname);
879 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
880 subnet->Netmask());
881 datapath_->RemoveOutboundIPv4(host_ifname);
882 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900883 return;
884 }
885
886 // Add the dupe fd to the epoll watcher.
887 // TODO(hugobenichi) Find a way to reuse base::FileDescriptorWatcher for
888 // listening to EPOLLHUP.
889 struct epoll_event epevent;
890 epevent.events = EPOLLIN; // EPOLLERR | EPOLLHUP are always waited for.
891 epevent.data.fd = local_client_fd.get();
892 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_ADD,
893 local_client_fd.get(), &epevent) != 0) {
894 PLOG(ERROR) << "ConnectNamespaceResponse: epoll_ctl(EPOLL_CTL_ADD) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900895 datapath_->RemoveInterface(host_ifname);
896 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
897 subnet->Netmask());
898 datapath_->RemoveOutboundIPv4(host_ifname);
899 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900900 return;
901 }
902
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900903 // Prepare the response before storing ConnectNamespaceInfo.
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900904 response.set_peer_ifname(client_ifname);
905 response.set_peer_ipv4_address(host_ipv4_addr);
906 response.set_host_ifname(host_ifname);
907 response.set_host_ipv4_address(client_ipv4_addr);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900908 auto* response_subnet = response.mutable_ipv4_subnet();
909 response_subnet->set_base_addr(subnet->BaseAddress());
910 response_subnet->set_prefix_len(subnet->PrefixLength());
911
912 // Store ConnectNamespaceInfo
913 connected_namespaces_next_id_++;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900914 int fdkey = local_client_fd.release();
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900915 connected_namespaces_[fdkey] = {};
916 ConnectNamespaceInfo& ns_info = connected_namespaces_[fdkey];
917 ns_info.pid = request.pid();
918 ns_info.outbound_ifname = request.outbound_physical_device();
919 ns_info.host_ifname = std::move(host_ifname);
920 ns_info.client_ifname = std::move(client_ifname);
921 ns_info.client_subnet = std::move(subnet);
922
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900923 LOG(INFO) << "Connected network namespace " << ns_info;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900924
925 if (connected_namespaces_.size() == 1) {
926 LOG(INFO) << "Starting ConnectNamespace client fds monitoring";
927 CheckConnectedNamespaces();
928 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900929}
930
931void Manager::DisconnectNamespace(int client_fd) {
932 auto it = connected_namespaces_.find(client_fd);
933 if (it == connected_namespaces_.end()) {
934 LOG(ERROR) << "No ConnectNamespaceInfo found for client_fd " << client_fd;
935 return;
936 }
937
Hugo Benichi7352ad92020-04-07 16:11:59 +0900938 // Remove the client fd dupe from the epoll watcher and close it.
939 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL, client_fd,
Hugo Benichie8758b52020-04-03 14:49:01 +0900940 nullptr) != 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900941 PLOG(ERROR) << "DisconnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900942 if (close(client_fd) < 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900943 PLOG(ERROR) << "DisconnectNamespace: close(client_fd) failed";
Hugo Benichi7352ad92020-04-07 16:11:59 +0900944
Hugo Benichie8758b52020-04-03 14:49:01 +0900945 // Destroy the interface configuration and routing configuration:
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900946 // - destroy veth pair.
Hugo Benichie8758b52020-04-03 14:49:01 +0900947 // - remove forwarding rules on host namespace.
948 // - remove SNAT marking rule on host namespace.
949 // Note that the default route set inside the client namespace by patchpanel
950 // is not destroyed: it is assumed the client will also teardown its
951 // namespace if it triggered DisconnectNamespace.
952 datapath_->RemoveInterface(it->second.host_ifname);
953 datapath_->RemoveOutboundIPv4(it->second.host_ifname);
954 datapath_->RemoveOutboundIPv4SNATMark(it->second.host_ifname);
955 datapath_->DeleteIPv4Route(it->second.client_subnet->AddressAtOffset(0),
956 it->second.client_subnet->BaseAddress(),
957 it->second.client_subnet->Netmask());
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900958
959 LOG(INFO) << "Disconnected network namespace " << it->second;
960
961 // This release the allocated IPv4 subnet.
962 connected_namespaces_.erase(it);
963}
964
Hugo Benichi7352ad92020-04-07 16:11:59 +0900965// TODO(hugobenichi) Generalize this check to all resources created by
966// patchpanel on behalf of a remote client.
967void Manager::CheckConnectedNamespaces() {
968 int max_event = 10;
969 struct epoll_event epevents[max_event];
970 int nready = epoll_wait(connected_namespaces_epollfd_, epevents, max_event,
971 0 /* do not block */);
972 if (nready < 0)
973 PLOG(ERROR) << "CheckConnectedNamespaces: epoll_wait(0) failed";
974
975 for (int i = 0; i < nready; i++)
976 if (epevents[i].events & (EPOLLHUP | EPOLLERR))
977 DisconnectNamespace(epevents[i].data.fd);
978
979 if (connected_namespaces_.empty()) {
980 LOG(INFO) << "Stopping ConnectNamespace client fds monitoring";
981 return;
982 }
983
Qijiang Fan2d7aeb42020-05-19 02:06:39 +0900984 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Hugo Benichi7352ad92020-04-07 16:11:59 +0900985 FROM_HERE,
986 base::Bind(&Manager::CheckConnectedNamespaces,
Hugo Benichie8758b52020-04-03 14:49:01 +0900987 weak_factory_.GetWeakPtr()),
Hugo Benichi7352ad92020-04-07 16:11:59 +0900988 kConnectNamespaceCheckInterval);
989}
990
Garrick Evanse94a14e2019-11-11 10:32:13 +0900991void Manager::SendGuestMessage(const GuestMessage& msg) {
Garrick Evans96e03042019-05-28 14:30:52 +0900992 IpHelperMessage ipm;
993 *ipm.mutable_guest_message() = msg;
Garrick Evans96e03042019-05-28 14:30:52 +0900994 adb_proxy_->SendMessage(ipm);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900995 mcast_proxy_->SendMessage(ipm);
996 nd_proxy_->SendMessage(ipm);
Garrick Evans96e03042019-05-28 14:30:52 +0900997}
998
Garrick Evans4ac09852020-01-16 14:09:22 +0900999void Manager::StartForwarding(const std::string& ifname_physical,
1000 const std::string& ifname_virtual,
Garrick Evans4ac09852020-01-16 14:09:22 +09001001 bool ipv6,
1002 bool multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001003 if (ifname_physical.empty() || ifname_virtual.empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001004 return;
1005
1006 IpHelperMessage ipm;
1007 DeviceMessage* msg = ipm.mutable_device_message();
1008 msg->set_dev_ifname(ifname_physical);
Garrick Evans4ac09852020-01-16 14:09:22 +09001009 msg->set_br_ifname(ifname_virtual);
1010
1011 if (ipv6) {
1012 LOG(INFO) << "Starting IPv6 forwarding from " << ifname_physical << " to "
1013 << ifname_virtual;
1014
1015 if (!datapath_->AddIPv6Forwarding(ifname_physical, ifname_virtual)) {
1016 LOG(ERROR) << "Failed to setup iptables forwarding rule for IPv6 from "
1017 << ifname_physical << " to " << ifname_virtual;
1018 }
1019 if (!datapath_->MaskInterfaceFlags(ifname_physical, IFF_ALLMULTI)) {
1020 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1021 << ifname_physical;
1022 }
1023 if (!datapath_->MaskInterfaceFlags(ifname_virtual, IFF_ALLMULTI)) {
1024 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1025 << ifname_virtual;
1026 }
1027 nd_proxy_->SendMessage(ipm);
1028 }
1029
1030 if (multicast) {
1031 LOG(INFO) << "Starting multicast forwarding from " << ifname_physical
1032 << " to " << ifname_virtual;
1033 mcast_proxy_->SendMessage(ipm);
1034 }
1035}
1036
1037void Manager::StopForwarding(const std::string& ifname_physical,
1038 const std::string& ifname_virtual,
1039 bool ipv6,
1040 bool multicast) {
1041 if (ifname_physical.empty())
1042 return;
1043
1044 IpHelperMessage ipm;
1045 DeviceMessage* msg = ipm.mutable_device_message();
1046 msg->set_dev_ifname(ifname_physical);
1047 msg->set_teardown(true);
Taoyu Li7dca19a2020-03-16 16:27:07 +09001048 if (!ifname_virtual.empty()) {
1049 msg->set_br_ifname(ifname_virtual);
1050 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001051
1052 if (ipv6) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001053 if (ifname_virtual.empty()) {
1054 LOG(INFO) << "Stopping IPv6 forwarding on " << ifname_physical;
1055 } else {
1056 LOG(INFO) << "Stopping IPv6 forwarding from " << ifname_physical << " to "
1057 << ifname_virtual;
1058 datapath_->RemoveIPv6Forwarding(ifname_physical, ifname_virtual);
1059 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001060 nd_proxy_->SendMessage(ipm);
1061 }
1062
1063 if (multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001064 if (ifname_virtual.empty()) {
1065 LOG(INFO) << "Stopping multicast forwarding on " << ifname_physical;
1066 } else {
1067 LOG(INFO) << "Stopping multicast forwarding from " << ifname_physical
1068 << " to " << ifname_virtual;
1069 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001070 mcast_proxy_->SendMessage(ipm);
1071 }
1072}
1073
Garrick Evans4ac09852020-01-16 14:09:22 +09001074void Manager::OnDeviceMessageFromNDProxy(const DeviceMessage& msg) {
1075 LOG_IF(DFATAL, msg.dev_ifname().empty())
1076 << "Received DeviceMessage w/ empty dev_ifname";
1077
1078 if (!datapath_->AddIPv6HostRoute(msg.dev_ifname(), msg.guest_ip6addr(),
1079 128)) {
1080 LOG(WARNING) << "Failed to setup the IPv6 route for interface "
1081 << msg.dev_ifname();
1082 }
1083}
1084
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001085std::ostream& operator<<(std::ostream& stream,
1086 const Manager::ConnectNamespaceInfo& ns_info) {
1087 stream << "{ pid: " << ns_info.pid;
1088 if (!ns_info.outbound_ifname.empty()) {
1089 stream << ", outbound_ifname: " << ns_info.outbound_ifname;
1090 }
1091 stream << ", host_ifname: " << ns_info.host_ifname
1092 << ", client_ifname: " << ns_info.client_ifname
1093 << ", subnet: " << ns_info.client_subnet->ToCidrString() << '}';
1094 return stream;
1095}
1096
Garrick Evans3388a032020-03-24 11:25:55 +09001097} // namespace patchpanel