blob: ff6496748bfa2f8c71b97cce877f8c7610082d9f [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
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900257 routing_svc_ = std::make_unique<RoutingService>();
258
Garrick Evans4ac09852020-01-16 14:09:22 +0900259 nd_proxy_->RegisterDeviceMessageHandler(base::Bind(
260 &Manager::OnDeviceMessageFromNDProxy, weak_factory_.GetWeakPtr()));
261
Garrick Evans69b85872020-02-04 11:40:26 +0900262 shill_client_ = std::make_unique<ShillClient>(bus_);
Garrick Evans1b1f67c2020-02-04 16:21:25 +0900263 auto* const forwarder = static_cast<TrafficForwarder*>(this);
Garrick Evans5d55f5e2019-07-17 15:28:10 +0900264
Garrick Evansf5862122020-03-16 09:13:45 +0900265 arc_svc_ = std::make_unique<ArcService>(
266 shill_client_.get(), datapath_.get(), &addr_mgr_, forwarder,
267 ShouldEnableFeature(kArcVmMultinetMinAndroidSdkVersion,
268 kArcVmMultinetMinChromeMilestone, {},
269 kArcVmMultinetFeatureName));
Garrick Evans1b1f67c2020-02-04 16:21:25 +0900270 cros_svc_ = std::make_unique<CrostiniService>(shill_client_.get(), &addr_mgr_,
271 datapath_.get(), forwarder);
Taoyu Liaf944c92019-10-01 12:22:31 +0900272
273 nd_proxy_->Listen();
Long Chengd4415582019-09-24 19:16:09 +0000274}
Garrick Evans49879532018-12-03 13:15:36 +0900275
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800276void Manager::OnShutdown(int* exit_code) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900277 LOG(INFO) << "Shutting down and cleaning up";
Garrick Evans207e7482019-12-16 11:54:36 +0900278 cros_svc_.reset();
279 arc_svc_.reset();
Hugo Benichi7352ad92020-04-07 16:11:59 +0900280 close(connected_namespaces_epollfd_);
Hugo Benichie8758b52020-04-03 14:49:01 +0900281 // Tear down any remaining connected namespace.
282 std::vector<int> connected_namespaces_fdkeys;
283 for (const auto& kv : connected_namespaces_)
284 connected_namespaces_fdkeys.push_back(kv.first);
285 for (const int fdkey : connected_namespaces_fdkeys)
286 DisconnectNamespace(fdkey);
Garrick Evans28d194e2019-12-17 10:22:28 +0900287
Garrick Evansd291af62020-05-25 10:39:06 +0900288 datapath_->RemoveForwardEstablishedRule();
289 datapath_->RemoveSNATMarkRules();
290
Garrick Evans7cf8c542020-05-25 09:50:17 +0900291 auto& runner = datapath_->runner();
Garrick Evans28d194e2019-12-17 10:22:28 +0900292 // Restore original local port range.
293 // TODO(garrick): The original history behind this tweak is gone. Some
294 // investigation is needed to see if it is still applicable.
Garrick Evans7cf8c542020-05-25 09:50:17 +0900295 if (runner.sysctl_w("net.ipv4.ip_local_port_range", "32768 61000") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900296 LOG(ERROR) << "Failed to restore local port range";
297 }
Garrick Evans7cf8c542020-05-25 09:50:17 +0900298 // Disable packet forwarding
299 if (runner.sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0) {
300 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
301 }
302 if (runner.sysctl_w("net.ipv4.ip_forward", "0") != 0) {
303 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
304 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800305}
306
Garrick Evans4c042572019-12-17 13:42:25 +0900307void Manager::OnSubprocessExited(pid_t pid, const siginfo_t&) {
308 LOG(ERROR) << "Subprocess " << pid << " exited unexpectedly -"
309 << " attempting to restart";
310
311 HelperProcess* proc;
312 if (pid == adb_proxy_->pid()) {
313 proc = adb_proxy_.get();
314 } else if (pid == mcast_proxy_->pid()) {
315 proc = mcast_proxy_.get();
316 } else if (pid == nd_proxy_->pid()) {
317 proc = nd_proxy_.get();
318 } else {
319 LOG(DFATAL) << "Unknown child process";
320 return;
321 }
322
323 process_reaper_.ForgetChild(pid);
324
hschamf9546312020-04-14 15:12:40 +0900325 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Garrick Evans4c042572019-12-17 13:42:25 +0900326 FROM_HERE,
327 base::Bind(&Manager::RestartSubprocess, weak_factory_.GetWeakPtr(), proc),
328 base::TimeDelta::FromMilliseconds((2 << proc->restarts()) *
329 kSubprocessRestartDelayMs));
330}
331
332void Manager::RestartSubprocess(HelperProcess* subproc) {
333 if (subproc->Restart()) {
334 DCHECK(process_reaper_.WatchForChild(
335 FROM_HERE, subproc->pid(),
336 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
337 subproc->pid())))
338 << "Failed to watch child process " << subproc->pid();
339 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800340}
341
Garrick Evanse94a14e2019-11-11 10:32:13 +0900342bool Manager::StartArc(pid_t pid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900343 if (!arc_svc_->Start(pid))
344 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900345
346 GuestMessage msg;
347 msg.set_event(GuestMessage::START);
348 msg.set_type(GuestMessage::ARC);
349 msg.set_arc_pid(pid);
350 SendGuestMessage(msg);
351
352 return true;
353}
354
Garrick Evans21173b12019-11-20 15:23:16 +0900355void Manager::StopArc(pid_t pid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900356 GuestMessage msg;
357 msg.set_event(GuestMessage::STOP);
358 msg.set_type(GuestMessage::ARC);
359 SendGuestMessage(msg);
360
Garrick Evans21173b12019-11-20 15:23:16 +0900361 arc_svc_->Stop(pid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900362}
363
Garrick Evans015b0d62020-02-07 09:06:38 +0900364bool Manager::StartArcVm(uint32_t cid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900365 if (!arc_svc_->Start(cid))
366 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900367
368 GuestMessage msg;
369 msg.set_event(GuestMessage::START);
370 msg.set_type(GuestMessage::ARC_VM);
371 msg.set_arcvm_vsock_cid(cid);
372 SendGuestMessage(msg);
373
374 return true;
375}
376
Garrick Evans015b0d62020-02-07 09:06:38 +0900377void Manager::StopArcVm(uint32_t cid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900378 GuestMessage msg;
379 msg.set_event(GuestMessage::STOP);
380 msg.set_type(GuestMessage::ARC_VM);
381 SendGuestMessage(msg);
382
Garrick Evans21173b12019-11-20 15:23:16 +0900383 arc_svc_->Stop(cid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900384}
385
Garrick Evans51d5b552020-01-30 10:42:06 +0900386bool Manager::StartCrosVm(uint64_t vm_id,
387 GuestMessage::GuestType vm_type,
Garrick Evans53a2a982020-02-05 10:53:35 +0900388 uint32_t subnet_index) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900389 DCHECK(vm_type == GuestMessage::TERMINA_VM ||
390 vm_type == GuestMessage::PLUGIN_VM);
391
392 if (!cros_svc_->Start(vm_id, vm_type == GuestMessage::TERMINA_VM,
393 subnet_index))
Garrick Evans47c19272019-11-21 10:58:21 +0900394 return false;
395
396 GuestMessage msg;
397 msg.set_event(GuestMessage::START);
Garrick Evans51d5b552020-01-30 10:42:06 +0900398 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900399 SendGuestMessage(msg);
400
401 return true;
402}
403
Garrick Evans51d5b552020-01-30 10:42:06 +0900404void Manager::StopCrosVm(uint64_t vm_id, GuestMessage::GuestType vm_type) {
Garrick Evans47c19272019-11-21 10:58:21 +0900405 GuestMessage msg;
406 msg.set_event(GuestMessage::STOP);
Garrick Evans51d5b552020-01-30 10:42:06 +0900407 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900408 SendGuestMessage(msg);
409
Garrick Evans51d5b552020-01-30 10:42:06 +0900410 cros_svc_->Stop(vm_id, vm_type == GuestMessage::TERMINA_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900411}
412
Garrick Evans08843932019-09-17 14:41:08 +0900413std::unique_ptr<dbus::Response> Manager::OnArcStartup(
414 dbus::MethodCall* method_call) {
415 LOG(INFO) << "ARC++ starting up";
416
417 std::unique_ptr<dbus::Response> dbus_response(
418 dbus::Response::FromMethodCall(method_call));
419
420 dbus::MessageReader reader(method_call);
421 dbus::MessageWriter writer(dbus_response.get());
422
423 patchpanel::ArcStartupRequest request;
424 patchpanel::ArcStartupResponse response;
425
426 if (!reader.PopArrayOfBytesAsProto(&request)) {
427 LOG(ERROR) << "Unable to parse request";
428 writer.AppendProtoAsArrayOfBytes(response);
429 return dbus_response;
430 }
431
Garrick Evanse01bf072019-11-15 09:08:19 +0900432 if (!StartArc(request.pid()))
433 LOG(ERROR) << "Failed to start ARC++ network service";
Garrick Evanse94a14e2019-11-11 10:32:13 +0900434
Garrick Evans08843932019-09-17 14:41:08 +0900435 writer.AppendProtoAsArrayOfBytes(response);
436 return dbus_response;
437}
438
439std::unique_ptr<dbus::Response> Manager::OnArcShutdown(
440 dbus::MethodCall* method_call) {
441 LOG(INFO) << "ARC++ shutting down";
442
443 std::unique_ptr<dbus::Response> dbus_response(
444 dbus::Response::FromMethodCall(method_call));
445
446 dbus::MessageReader reader(method_call);
447 dbus::MessageWriter writer(dbus_response.get());
448
449 patchpanel::ArcShutdownRequest request;
450 patchpanel::ArcShutdownResponse response;
451
452 if (!reader.PopArrayOfBytesAsProto(&request)) {
453 LOG(ERROR) << "Unable to parse request";
454 writer.AppendProtoAsArrayOfBytes(response);
455 return dbus_response;
456 }
457
Garrick Evans21173b12019-11-20 15:23:16 +0900458 StopArc(request.pid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900459
Garrick Evans08843932019-09-17 14:41:08 +0900460 writer.AppendProtoAsArrayOfBytes(response);
461 return dbus_response;
462}
463
464std::unique_ptr<dbus::Response> Manager::OnArcVmStartup(
465 dbus::MethodCall* method_call) {
466 LOG(INFO) << "ARCVM starting up";
467
468 std::unique_ptr<dbus::Response> dbus_response(
469 dbus::Response::FromMethodCall(method_call));
470
471 dbus::MessageReader reader(method_call);
472 dbus::MessageWriter writer(dbus_response.get());
473
474 patchpanel::ArcVmStartupRequest request;
475 patchpanel::ArcVmStartupResponse response;
476
477 if (!reader.PopArrayOfBytesAsProto(&request)) {
478 LOG(ERROR) << "Unable to parse request";
479 writer.AppendProtoAsArrayOfBytes(response);
480 return dbus_response;
481 }
482
Garrick Evans47c19272019-11-21 10:58:21 +0900483 if (!StartArcVm(request.cid())) {
Garrick Evanse01bf072019-11-15 09:08:19 +0900484 LOG(ERROR) << "Failed to start ARCVM network service";
Garrick Evans47c19272019-11-21 10:58:21 +0900485 writer.AppendProtoAsArrayOfBytes(response);
486 return dbus_response;
Garrick Evanse01bf072019-11-15 09:08:19 +0900487 }
Garrick Evanse94a14e2019-11-11 10:32:13 +0900488
Garrick Evans47c19272019-11-21 10:58:21 +0900489 // Populate the response with the known devices.
Garrick Evans38b25a42020-04-06 15:17:42 +0900490 for (const auto* config : arc_svc_->GetDeviceConfigs()) {
491 if (config->tap_ifname().empty())
492 continue;
Garrick Evans47c19272019-11-21 10:58:21 +0900493
Garrick Evans38b25a42020-04-06 15:17:42 +0900494 auto* dev = response.add_devices();
495 dev->set_ifname(config->tap_ifname());
496 dev->set_ipv4_addr(config->guest_ipv4_addr());
497 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900498
Garrick Evans08843932019-09-17 14:41:08 +0900499 writer.AppendProtoAsArrayOfBytes(response);
500 return dbus_response;
501}
502
503std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
504 dbus::MethodCall* method_call) {
505 LOG(INFO) << "ARCVM shutting down";
506
507 std::unique_ptr<dbus::Response> dbus_response(
508 dbus::Response::FromMethodCall(method_call));
509
510 dbus::MessageReader reader(method_call);
511 dbus::MessageWriter writer(dbus_response.get());
512
513 patchpanel::ArcVmShutdownRequest request;
514 patchpanel::ArcVmShutdownResponse response;
515
516 if (!reader.PopArrayOfBytesAsProto(&request)) {
517 LOG(ERROR) << "Unable to parse request";
518 writer.AppendProtoAsArrayOfBytes(response);
519 return dbus_response;
520 }
521
Garrick Evans21173b12019-11-20 15:23:16 +0900522 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900523
Garrick Evans08843932019-09-17 14:41:08 +0900524 writer.AppendProtoAsArrayOfBytes(response);
525 return dbus_response;
526}
527
Garrick Evans47c19272019-11-21 10:58:21 +0900528std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
529 dbus::MethodCall* method_call) {
530 LOG(INFO) << "Termina VM starting up";
531
532 std::unique_ptr<dbus::Response> dbus_response(
533 dbus::Response::FromMethodCall(method_call));
534
535 dbus::MessageReader reader(method_call);
536 dbus::MessageWriter writer(dbus_response.get());
537
538 patchpanel::TerminaVmStartupRequest request;
539 patchpanel::TerminaVmStartupResponse response;
540
541 if (!reader.PopArrayOfBytesAsProto(&request)) {
542 LOG(ERROR) << "Unable to parse request";
543 writer.AppendProtoAsArrayOfBytes(response);
544 return dbus_response;
545 }
546
547 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900548 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900549 LOG(ERROR) << "Failed to start Termina VM network service";
550 writer.AppendProtoAsArrayOfBytes(response);
551 return dbus_response;
552 }
553
Garrick Evans51d5b552020-01-30 10:42:06 +0900554 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900555 if (!tap) {
556 LOG(DFATAL) << "TAP device missing";
557 writer.AppendProtoAsArrayOfBytes(response);
558 return dbus_response;
559 }
Garrick Evans47c19272019-11-21 10:58:21 +0900560
Garrick Evansb1c93712020-01-22 09:28:25 +0900561 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900562 dev->set_ifname(tap->host_ifname());
563 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900564 if (!subnet) {
565 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
566 writer.AppendProtoAsArrayOfBytes(response);
567 return dbus_response;
568 }
569 auto* resp_subnet = dev->mutable_ipv4_subnet();
570 resp_subnet->set_base_addr(subnet->BaseAddress());
571 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900572 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900573 if (!subnet) {
574 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
575 writer.AppendProtoAsArrayOfBytes(response);
576 return dbus_response;
577 }
578 resp_subnet = response.mutable_container_subnet();
579 resp_subnet->set_base_addr(subnet->BaseAddress());
580 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900581
582 writer.AppendProtoAsArrayOfBytes(response);
583 return dbus_response;
584}
585
586std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
587 dbus::MethodCall* method_call) {
588 LOG(INFO) << "Termina VM shutting down";
589
590 std::unique_ptr<dbus::Response> dbus_response(
591 dbus::Response::FromMethodCall(method_call));
592
593 dbus::MessageReader reader(method_call);
594 dbus::MessageWriter writer(dbus_response.get());
595
596 patchpanel::TerminaVmShutdownRequest request;
597 patchpanel::TerminaVmShutdownResponse response;
598
599 if (!reader.PopArrayOfBytesAsProto(&request)) {
600 LOG(ERROR) << "Unable to parse request";
601 writer.AppendProtoAsArrayOfBytes(response);
602 return dbus_response;
603 }
604
Garrick Evans51d5b552020-01-30 10:42:06 +0900605 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
606
607 writer.AppendProtoAsArrayOfBytes(response);
608 return dbus_response;
609}
610
611std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
612 dbus::MethodCall* method_call) {
613 LOG(INFO) << "Plugin VM starting up";
614
615 std::unique_ptr<dbus::Response> dbus_response(
616 dbus::Response::FromMethodCall(method_call));
617
618 dbus::MessageReader reader(method_call);
619 dbus::MessageWriter writer(dbus_response.get());
620
621 patchpanel::PluginVmStartupRequest request;
622 patchpanel::PluginVmStartupResponse response;
623
624 if (!reader.PopArrayOfBytesAsProto(&request)) {
625 LOG(ERROR) << "Unable to parse request";
626 writer.AppendProtoAsArrayOfBytes(response);
627 return dbus_response;
628 }
629
Garrick Evans08fb34b2020-02-20 10:50:17 +0900630 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900631 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900632 LOG(ERROR) << "Failed to start Plugin VM network service";
633 writer.AppendProtoAsArrayOfBytes(response);
634 return dbus_response;
635 }
636
637 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
638 if (!tap) {
639 LOG(DFATAL) << "TAP device missing";
640 writer.AppendProtoAsArrayOfBytes(response);
641 return dbus_response;
642 }
643
Garrick Evans51d5b552020-01-30 10:42:06 +0900644 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900645 dev->set_ifname(tap->host_ifname());
646 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900647 if (!subnet) {
648 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
649 writer.AppendProtoAsArrayOfBytes(response);
650 return dbus_response;
651 }
652 auto* resp_subnet = dev->mutable_ipv4_subnet();
653 resp_subnet->set_base_addr(subnet->BaseAddress());
654 resp_subnet->set_prefix_len(subnet->PrefixLength());
655
656 writer.AppendProtoAsArrayOfBytes(response);
657 return dbus_response;
658}
659
660std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
661 dbus::MethodCall* method_call) {
662 LOG(INFO) << "Plugin VM shutting down";
663
664 std::unique_ptr<dbus::Response> dbus_response(
665 dbus::Response::FromMethodCall(method_call));
666
667 dbus::MessageReader reader(method_call);
668 dbus::MessageWriter writer(dbus_response.get());
669
670 patchpanel::PluginVmShutdownRequest request;
671 patchpanel::PluginVmShutdownResponse response;
672
673 if (!reader.PopArrayOfBytesAsProto(&request)) {
674 LOG(ERROR) << "Unable to parse request";
675 writer.AppendProtoAsArrayOfBytes(response);
676 return dbus_response;
677 }
678
679 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900680
681 writer.AppendProtoAsArrayOfBytes(response);
682 return dbus_response;
683}
684
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900685std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
686 dbus::MethodCall* method_call) {
687 std::unique_ptr<dbus::Response> dbus_response(
688 dbus::Response::FromMethodCall(method_call));
689
690 dbus::MessageReader reader(method_call);
691 dbus::MessageWriter writer(dbus_response.get());
692
693 patchpanel::SetVpnIntentRequest request;
694 patchpanel::SetVpnIntentResponse response;
695
696 bool success = reader.PopArrayOfBytesAsProto(&request);
697 if (!success) {
698 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
699 // Do not return yet to make sure we close the received fd.
700 }
701
702 base::ScopedFD client_socket;
703 reader.PopFileDescriptor(&client_socket);
704
705 if (success)
706 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
707
708 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900709
710 writer.AppendProtoAsArrayOfBytes(response);
711 return dbus_response;
712}
713
714std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
715 dbus::MethodCall* method_call) {
716 std::unique_ptr<dbus::Response> dbus_response(
717 dbus::Response::FromMethodCall(method_call));
718
719 dbus::MessageReader reader(method_call);
720 dbus::MessageWriter writer(dbus_response.get());
721
722 patchpanel::ConnectNamespaceRequest request;
723 patchpanel::ConnectNamespaceResponse response;
724
Hugo Benichicc6850f2020-01-17 13:26:06 +0900725 bool success = true;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900726 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900727 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
728 // Do not return yet to make sure we close the received fd and
729 // validate other arguments.
730 success = false;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900731 }
732
Hugo Benichicc6850f2020-01-17 13:26:06 +0900733 base::ScopedFD client_fd;
734 reader.PopFileDescriptor(&client_fd);
735 if (!client_fd.is_valid()) {
736 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
737 success = false;
738 }
739
740 pid_t pid = request.pid();
741 {
742 ScopedNS ns(pid);
743 if (!ns.IsValid()) {
744 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
745 success = false;
746 }
747 }
748
749 const std::string& outbound_ifname = request.outbound_physical_device();
750 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
751 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
752 << outbound_ifname;
753 success = false;
754 }
755
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900756 if (success)
757 ConnectNamespace(std::move(client_fd), request, response);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900758
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900759 writer.AppendProtoAsArrayOfBytes(response);
760 return dbus_response;
761}
762
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900763void Manager::ConnectNamespace(
764 base::ScopedFD client_fd,
765 const patchpanel::ConnectNamespaceRequest& request,
766 patchpanel::ConnectNamespaceResponse& response) {
767 std::unique_ptr<Subnet> subnet =
768 addr_mgr_.AllocateIPv4Subnet(AddressManager::Guest::MINIJAIL_NETNS);
769 if (!subnet) {
770 LOG(ERROR) << "ConnectNamespaceRequest: exhausted IPv4 subnet space";
771 return;
772 }
773
774 const std::string ifname_id = std::to_string(connected_namespaces_next_id_);
775 const std::string host_ifname = "arc_ns" + ifname_id;
776 const std::string client_ifname = "veth" + ifname_id;
Hugo Benichie8758b52020-04-03 14:49:01 +0900777 const uint32_t host_ipv4_addr = subnet->AddressAtOffset(0);
778 const uint32_t client_ipv4_addr = subnet->AddressAtOffset(1);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900779
Hugo Benichie8758b52020-04-03 14:49:01 +0900780 // Veth interface configuration and client routing configuration:
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900781 // - create veth pair inside client namespace.
782 // - configure IPv4 address on remote veth inside client namespace.
Hugo Benichie8758b52020-04-03 14:49:01 +0900783 // - configure IPv4 address on local veth inside host namespace.
784 // - add a default IPv4 /0 route sending traffic to that remote veth.
785 // - bring back one veth to the host namespace, and set it up.
786 pid_t pid = request.pid();
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900787 if (!datapath_->ConnectVethPair(pid, host_ifname, client_ifname,
788 addr_mgr_.GenerateMacAddress(),
789 client_ipv4_addr, subnet->PrefixLength(),
790 false /* enable_multicast */)) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900791 LOG(ERROR) << "ConnectNamespaceRequest: failed to create veth pair for "
792 "namespace pid "
793 << pid;
794 return;
795 }
796 if (!datapath_->ConfigureInterface(
797 host_ifname, addr_mgr_.GenerateMacAddress(), host_ipv4_addr,
798 subnet->PrefixLength(), true /* link up */,
799 false /* enable_multicast */)) {
800 LOG(ERROR) << "ConnectNamespaceRequest: cannot configure host interface "
801 << host_ifname;
802 datapath_->RemoveInterface(host_ifname);
803 return;
804 }
805 {
806 ScopedNS ns(pid);
807 if (!ns.IsValid()) {
808 LOG(ERROR) << "ConnectNamespaceRequest: cannot enter client pid " << pid;
809 datapath_->RemoveInterface(host_ifname);
810 return;
811 }
812 if (!datapath_->AddIPv4Route(host_ipv4_addr, INADDR_ANY, INADDR_ANY)) {
813 LOG(ERROR)
814 << "ConnectNamespaceRequest: failed to add default /0 route to "
815 << host_ifname << " inside namespace pid " << pid;
816 datapath_->RemoveInterface(host_ifname);
817 return;
818 }
819 }
820
821 // Host namespace routing configuration
822 // - ingress: add route to client subnet via |host_ifname|.
823 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
824 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
825 // Note that by default unsolicited ingress traffic is not forwarded to the
826 // client namespace unless the client specifically set port forwarding
827 // through permission_broker DBus APIs.
828 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
829 // both ways between client namespace and other guest containers and VMs.
830 // TODO(hugobenichi) If outbound_physical_device is defined, then set strong
831 // routing to that interface routing table.
832 if (!datapath_->AddIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
833 subnet->Netmask())) {
834 LOG(ERROR)
835 << "ConnectNamespaceRequest: failed to set route to client namespace";
836 datapath_->RemoveInterface(host_ifname);
837 return;
838 }
839 if (!datapath_->AddOutboundIPv4(host_ifname)) {
840 LOG(ERROR) << "ConnectNamespaceRequest: failed to allow FORWARD for "
841 "traffic outgoing from "
842 << host_ifname;
843 datapath_->RemoveInterface(host_ifname);
844 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
845 subnet->Netmask());
846 return;
847 }
848 if (!datapath_->AddOutboundIPv4SNATMark(host_ifname)) {
849 LOG(ERROR) << "ConnectNamespaceRequest: failed to set SNAT for traffic "
850 "outgoing from "
851 << host_ifname;
852 datapath_->RemoveInterface(host_ifname);
853 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
854 subnet->Netmask());
855 datapath_->RemoveOutboundIPv4(host_ifname);
856 return;
857 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900858
Hugo Benichi7352ad92020-04-07 16:11:59 +0900859 // Dup the client fd into our own: this guarantees that the fd number will
860 // be stable and tied to the actual kernel resources used by the client.
861 base::ScopedFD local_client_fd(dup(client_fd.get()));
862 if (!local_client_fd.is_valid()) {
863 PLOG(ERROR) << "ConnectNamespaceRequest: failed to dup() client fd";
Hugo Benichie8758b52020-04-03 14:49:01 +0900864 datapath_->RemoveInterface(host_ifname);
865 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
866 subnet->Netmask());
867 datapath_->RemoveOutboundIPv4(host_ifname);
868 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900869 return;
870 }
871
872 // Add the dupe fd to the epoll watcher.
873 // TODO(hugobenichi) Find a way to reuse base::FileDescriptorWatcher for
874 // listening to EPOLLHUP.
875 struct epoll_event epevent;
876 epevent.events = EPOLLIN; // EPOLLERR | EPOLLHUP are always waited for.
877 epevent.data.fd = local_client_fd.get();
878 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_ADD,
879 local_client_fd.get(), &epevent) != 0) {
880 PLOG(ERROR) << "ConnectNamespaceResponse: epoll_ctl(EPOLL_CTL_ADD) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900881 datapath_->RemoveInterface(host_ifname);
882 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
883 subnet->Netmask());
884 datapath_->RemoveOutboundIPv4(host_ifname);
885 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900886 return;
887 }
888
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900889 // Prepare the response before storing ConnectNamespaceInfo.
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900890 response.set_peer_ifname(client_ifname);
891 response.set_peer_ipv4_address(host_ipv4_addr);
892 response.set_host_ifname(host_ifname);
893 response.set_host_ipv4_address(client_ipv4_addr);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900894 auto* response_subnet = response.mutable_ipv4_subnet();
895 response_subnet->set_base_addr(subnet->BaseAddress());
896 response_subnet->set_prefix_len(subnet->PrefixLength());
897
898 // Store ConnectNamespaceInfo
899 connected_namespaces_next_id_++;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900900 int fdkey = local_client_fd.release();
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900901 connected_namespaces_[fdkey] = {};
902 ConnectNamespaceInfo& ns_info = connected_namespaces_[fdkey];
903 ns_info.pid = request.pid();
904 ns_info.outbound_ifname = request.outbound_physical_device();
905 ns_info.host_ifname = std::move(host_ifname);
906 ns_info.client_ifname = std::move(client_ifname);
907 ns_info.client_subnet = std::move(subnet);
908
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900909 LOG(INFO) << "Connected network namespace " << ns_info;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900910
911 if (connected_namespaces_.size() == 1) {
912 LOG(INFO) << "Starting ConnectNamespace client fds monitoring";
913 CheckConnectedNamespaces();
914 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900915}
916
917void Manager::DisconnectNamespace(int client_fd) {
918 auto it = connected_namespaces_.find(client_fd);
919 if (it == connected_namespaces_.end()) {
920 LOG(ERROR) << "No ConnectNamespaceInfo found for client_fd " << client_fd;
921 return;
922 }
923
Hugo Benichi7352ad92020-04-07 16:11:59 +0900924 // Remove the client fd dupe from the epoll watcher and close it.
925 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL, client_fd,
Hugo Benichie8758b52020-04-03 14:49:01 +0900926 nullptr) != 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900927 PLOG(ERROR) << "DisconnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900928 if (close(client_fd) < 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900929 PLOG(ERROR) << "DisconnectNamespace: close(client_fd) failed";
Hugo Benichi7352ad92020-04-07 16:11:59 +0900930
Hugo Benichie8758b52020-04-03 14:49:01 +0900931 // Destroy the interface configuration and routing configuration:
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900932 // - destroy veth pair.
Hugo Benichie8758b52020-04-03 14:49:01 +0900933 // - remove forwarding rules on host namespace.
934 // - remove SNAT marking rule on host namespace.
935 // Note that the default route set inside the client namespace by patchpanel
936 // is not destroyed: it is assumed the client will also teardown its
937 // namespace if it triggered DisconnectNamespace.
938 datapath_->RemoveInterface(it->second.host_ifname);
939 datapath_->RemoveOutboundIPv4(it->second.host_ifname);
940 datapath_->RemoveOutboundIPv4SNATMark(it->second.host_ifname);
941 datapath_->DeleteIPv4Route(it->second.client_subnet->AddressAtOffset(0),
942 it->second.client_subnet->BaseAddress(),
943 it->second.client_subnet->Netmask());
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900944
945 LOG(INFO) << "Disconnected network namespace " << it->second;
946
947 // This release the allocated IPv4 subnet.
948 connected_namespaces_.erase(it);
949}
950
Hugo Benichi7352ad92020-04-07 16:11:59 +0900951// TODO(hugobenichi) Generalize this check to all resources created by
952// patchpanel on behalf of a remote client.
953void Manager::CheckConnectedNamespaces() {
954 int max_event = 10;
955 struct epoll_event epevents[max_event];
956 int nready = epoll_wait(connected_namespaces_epollfd_, epevents, max_event,
957 0 /* do not block */);
958 if (nready < 0)
959 PLOG(ERROR) << "CheckConnectedNamespaces: epoll_wait(0) failed";
960
961 for (int i = 0; i < nready; i++)
962 if (epevents[i].events & (EPOLLHUP | EPOLLERR))
963 DisconnectNamespace(epevents[i].data.fd);
964
965 if (connected_namespaces_.empty()) {
966 LOG(INFO) << "Stopping ConnectNamespace client fds monitoring";
967 return;
968 }
969
Qijiang Fan2d7aeb42020-05-19 02:06:39 +0900970 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Hugo Benichi7352ad92020-04-07 16:11:59 +0900971 FROM_HERE,
972 base::Bind(&Manager::CheckConnectedNamespaces,
Hugo Benichie8758b52020-04-03 14:49:01 +0900973 weak_factory_.GetWeakPtr()),
Hugo Benichi7352ad92020-04-07 16:11:59 +0900974 kConnectNamespaceCheckInterval);
975}
976
Garrick Evanse94a14e2019-11-11 10:32:13 +0900977void Manager::SendGuestMessage(const GuestMessage& msg) {
Garrick Evans96e03042019-05-28 14:30:52 +0900978 IpHelperMessage ipm;
979 *ipm.mutable_guest_message() = msg;
Garrick Evans96e03042019-05-28 14:30:52 +0900980 adb_proxy_->SendMessage(ipm);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900981 mcast_proxy_->SendMessage(ipm);
982 nd_proxy_->SendMessage(ipm);
Garrick Evans96e03042019-05-28 14:30:52 +0900983}
984
Garrick Evans4ac09852020-01-16 14:09:22 +0900985void Manager::StartForwarding(const std::string& ifname_physical,
986 const std::string& ifname_virtual,
Garrick Evans4ac09852020-01-16 14:09:22 +0900987 bool ipv6,
988 bool multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +0900989 if (ifname_physical.empty() || ifname_virtual.empty())
Garrick Evans4ac09852020-01-16 14:09:22 +0900990 return;
991
992 IpHelperMessage ipm;
993 DeviceMessage* msg = ipm.mutable_device_message();
994 msg->set_dev_ifname(ifname_physical);
Garrick Evans4ac09852020-01-16 14:09:22 +0900995 msg->set_br_ifname(ifname_virtual);
996
997 if (ipv6) {
998 LOG(INFO) << "Starting IPv6 forwarding from " << ifname_physical << " to "
999 << ifname_virtual;
1000
1001 if (!datapath_->AddIPv6Forwarding(ifname_physical, ifname_virtual)) {
1002 LOG(ERROR) << "Failed to setup iptables forwarding rule for IPv6 from "
1003 << ifname_physical << " to " << ifname_virtual;
1004 }
1005 if (!datapath_->MaskInterfaceFlags(ifname_physical, IFF_ALLMULTI)) {
1006 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1007 << ifname_physical;
1008 }
1009 if (!datapath_->MaskInterfaceFlags(ifname_virtual, IFF_ALLMULTI)) {
1010 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1011 << ifname_virtual;
1012 }
1013 nd_proxy_->SendMessage(ipm);
1014 }
1015
1016 if (multicast) {
1017 LOG(INFO) << "Starting multicast forwarding from " << ifname_physical
1018 << " to " << ifname_virtual;
1019 mcast_proxy_->SendMessage(ipm);
1020 }
1021}
1022
1023void Manager::StopForwarding(const std::string& ifname_physical,
1024 const std::string& ifname_virtual,
1025 bool ipv6,
1026 bool multicast) {
1027 if (ifname_physical.empty())
1028 return;
1029
1030 IpHelperMessage ipm;
1031 DeviceMessage* msg = ipm.mutable_device_message();
1032 msg->set_dev_ifname(ifname_physical);
1033 msg->set_teardown(true);
Taoyu Li7dca19a2020-03-16 16:27:07 +09001034 if (!ifname_virtual.empty()) {
1035 msg->set_br_ifname(ifname_virtual);
1036 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001037
1038 if (ipv6) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001039 if (ifname_virtual.empty()) {
1040 LOG(INFO) << "Stopping IPv6 forwarding on " << ifname_physical;
1041 } else {
1042 LOG(INFO) << "Stopping IPv6 forwarding from " << ifname_physical << " to "
1043 << ifname_virtual;
1044 datapath_->RemoveIPv6Forwarding(ifname_physical, ifname_virtual);
1045 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001046 nd_proxy_->SendMessage(ipm);
1047 }
1048
1049 if (multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001050 if (ifname_virtual.empty()) {
1051 LOG(INFO) << "Stopping multicast forwarding on " << ifname_physical;
1052 } else {
1053 LOG(INFO) << "Stopping multicast forwarding from " << ifname_physical
1054 << " to " << ifname_virtual;
1055 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001056 mcast_proxy_->SendMessage(ipm);
1057 }
1058}
1059
Garrick Evans4ac09852020-01-16 14:09:22 +09001060void Manager::OnDeviceMessageFromNDProxy(const DeviceMessage& msg) {
1061 LOG_IF(DFATAL, msg.dev_ifname().empty())
1062 << "Received DeviceMessage w/ empty dev_ifname";
1063
1064 if (!datapath_->AddIPv6HostRoute(msg.dev_ifname(), msg.guest_ip6addr(),
1065 128)) {
1066 LOG(WARNING) << "Failed to setup the IPv6 route for interface "
1067 << msg.dev_ifname();
1068 }
1069}
1070
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001071std::ostream& operator<<(std::ostream& stream,
1072 const Manager::ConnectNamespaceInfo& ns_info) {
1073 stream << "{ pid: " << ns_info.pid;
1074 if (!ns_info.outbound_ifname.empty()) {
1075 stream << ", outbound_ifname: " << ns_info.outbound_ifname;
1076 }
1077 stream << ", host_ifname: " << ns_info.host_ifname
1078 << ", client_ifname: " << ns_info.client_ifname
1079 << ", subnet: " << ns_info.client_subnet->ToCidrString() << '}';
1080 return stream;
1081}
1082
Garrick Evans3388a032020-03-24 11:25:55 +09001083} // namespace patchpanel