blob: f833159e419dd75e3760db6befd73d8be1ed6149 [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
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900248 routing_svc_ = std::make_unique<RoutingService>();
249
Garrick Evans4ac09852020-01-16 14:09:22 +0900250 nd_proxy_->RegisterDeviceMessageHandler(base::Bind(
251 &Manager::OnDeviceMessageFromNDProxy, weak_factory_.GetWeakPtr()));
252
Garrick Evans69b85872020-02-04 11:40:26 +0900253 shill_client_ = std::make_unique<ShillClient>(bus_);
Garrick Evans1b1f67c2020-02-04 16:21:25 +0900254 auto* const forwarder = static_cast<TrafficForwarder*>(this);
Garrick Evans5d55f5e2019-07-17 15:28:10 +0900255
Garrick Evansf5862122020-03-16 09:13:45 +0900256 arc_svc_ = std::make_unique<ArcService>(
257 shill_client_.get(), datapath_.get(), &addr_mgr_, forwarder,
258 ShouldEnableFeature(kArcVmMultinetMinAndroidSdkVersion,
259 kArcVmMultinetMinChromeMilestone, {},
260 kArcVmMultinetFeatureName));
Garrick Evans1b1f67c2020-02-04 16:21:25 +0900261 cros_svc_ = std::make_unique<CrostiniService>(shill_client_.get(), &addr_mgr_,
262 datapath_.get(), forwarder);
Taoyu Liaf944c92019-10-01 12:22:31 +0900263
264 nd_proxy_->Listen();
Long Chengd4415582019-09-24 19:16:09 +0000265}
Garrick Evans49879532018-12-03 13:15:36 +0900266
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800267void Manager::OnShutdown(int* exit_code) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900268 LOG(INFO) << "Shutting down and cleaning up";
Garrick Evans207e7482019-12-16 11:54:36 +0900269 cros_svc_.reset();
270 arc_svc_.reset();
Hugo Benichi7352ad92020-04-07 16:11:59 +0900271 close(connected_namespaces_epollfd_);
Hugo Benichie8758b52020-04-03 14:49:01 +0900272 // Tear down any remaining connected namespace.
273 std::vector<int> connected_namespaces_fdkeys;
274 for (const auto& kv : connected_namespaces_)
275 connected_namespaces_fdkeys.push_back(kv.first);
276 for (const int fdkey : connected_namespaces_fdkeys)
277 DisconnectNamespace(fdkey);
Garrick Evans28d194e2019-12-17 10:22:28 +0900278
Garrick Evans7cf8c542020-05-25 09:50:17 +0900279 auto& runner = datapath_->runner();
Garrick Evans28d194e2019-12-17 10:22:28 +0900280 // Restore original local port range.
281 // TODO(garrick): The original history behind this tweak is gone. Some
282 // investigation is needed to see if it is still applicable.
Garrick Evans7cf8c542020-05-25 09:50:17 +0900283 if (runner.sysctl_w("net.ipv4.ip_local_port_range", "32768 61000") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900284 LOG(ERROR) << "Failed to restore local port range";
285 }
Garrick Evans7cf8c542020-05-25 09:50:17 +0900286 // Disable packet forwarding
287 if (runner.sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0) {
288 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
289 }
290 if (runner.sysctl_w("net.ipv4.ip_forward", "0") != 0) {
291 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
292 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800293}
294
Garrick Evans4c042572019-12-17 13:42:25 +0900295void Manager::OnSubprocessExited(pid_t pid, const siginfo_t&) {
296 LOG(ERROR) << "Subprocess " << pid << " exited unexpectedly -"
297 << " attempting to restart";
298
299 HelperProcess* proc;
300 if (pid == adb_proxy_->pid()) {
301 proc = adb_proxy_.get();
302 } else if (pid == mcast_proxy_->pid()) {
303 proc = mcast_proxy_.get();
304 } else if (pid == nd_proxy_->pid()) {
305 proc = nd_proxy_.get();
306 } else {
307 LOG(DFATAL) << "Unknown child process";
308 return;
309 }
310
311 process_reaper_.ForgetChild(pid);
312
hschamf9546312020-04-14 15:12:40 +0900313 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Garrick Evans4c042572019-12-17 13:42:25 +0900314 FROM_HERE,
315 base::Bind(&Manager::RestartSubprocess, weak_factory_.GetWeakPtr(), proc),
316 base::TimeDelta::FromMilliseconds((2 << proc->restarts()) *
317 kSubprocessRestartDelayMs));
318}
319
320void Manager::RestartSubprocess(HelperProcess* subproc) {
321 if (subproc->Restart()) {
322 DCHECK(process_reaper_.WatchForChild(
323 FROM_HERE, subproc->pid(),
324 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
325 subproc->pid())))
326 << "Failed to watch child process " << subproc->pid();
327 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800328}
329
Garrick Evanse94a14e2019-11-11 10:32:13 +0900330bool Manager::StartArc(pid_t pid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900331 if (!arc_svc_->Start(pid))
332 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900333
334 GuestMessage msg;
335 msg.set_event(GuestMessage::START);
336 msg.set_type(GuestMessage::ARC);
337 msg.set_arc_pid(pid);
338 SendGuestMessage(msg);
339
340 return true;
341}
342
Garrick Evans21173b12019-11-20 15:23:16 +0900343void Manager::StopArc(pid_t pid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900344 GuestMessage msg;
345 msg.set_event(GuestMessage::STOP);
346 msg.set_type(GuestMessage::ARC);
347 SendGuestMessage(msg);
348
Garrick Evans21173b12019-11-20 15:23:16 +0900349 arc_svc_->Stop(pid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900350}
351
Garrick Evans015b0d62020-02-07 09:06:38 +0900352bool Manager::StartArcVm(uint32_t cid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900353 if (!arc_svc_->Start(cid))
354 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900355
356 GuestMessage msg;
357 msg.set_event(GuestMessage::START);
358 msg.set_type(GuestMessage::ARC_VM);
359 msg.set_arcvm_vsock_cid(cid);
360 SendGuestMessage(msg);
361
362 return true;
363}
364
Garrick Evans015b0d62020-02-07 09:06:38 +0900365void Manager::StopArcVm(uint32_t cid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900366 GuestMessage msg;
367 msg.set_event(GuestMessage::STOP);
368 msg.set_type(GuestMessage::ARC_VM);
369 SendGuestMessage(msg);
370
Garrick Evans21173b12019-11-20 15:23:16 +0900371 arc_svc_->Stop(cid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900372}
373
Garrick Evans51d5b552020-01-30 10:42:06 +0900374bool Manager::StartCrosVm(uint64_t vm_id,
375 GuestMessage::GuestType vm_type,
Garrick Evans53a2a982020-02-05 10:53:35 +0900376 uint32_t subnet_index) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900377 DCHECK(vm_type == GuestMessage::TERMINA_VM ||
378 vm_type == GuestMessage::PLUGIN_VM);
379
380 if (!cros_svc_->Start(vm_id, vm_type == GuestMessage::TERMINA_VM,
381 subnet_index))
Garrick Evans47c19272019-11-21 10:58:21 +0900382 return false;
383
384 GuestMessage msg;
385 msg.set_event(GuestMessage::START);
Garrick Evans51d5b552020-01-30 10:42:06 +0900386 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900387 SendGuestMessage(msg);
388
389 return true;
390}
391
Garrick Evans51d5b552020-01-30 10:42:06 +0900392void Manager::StopCrosVm(uint64_t vm_id, GuestMessage::GuestType vm_type) {
Garrick Evans47c19272019-11-21 10:58:21 +0900393 GuestMessage msg;
394 msg.set_event(GuestMessage::STOP);
Garrick Evans51d5b552020-01-30 10:42:06 +0900395 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900396 SendGuestMessage(msg);
397
Garrick Evans51d5b552020-01-30 10:42:06 +0900398 cros_svc_->Stop(vm_id, vm_type == GuestMessage::TERMINA_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900399}
400
Garrick Evans08843932019-09-17 14:41:08 +0900401std::unique_ptr<dbus::Response> Manager::OnArcStartup(
402 dbus::MethodCall* method_call) {
403 LOG(INFO) << "ARC++ starting up";
404
405 std::unique_ptr<dbus::Response> dbus_response(
406 dbus::Response::FromMethodCall(method_call));
407
408 dbus::MessageReader reader(method_call);
409 dbus::MessageWriter writer(dbus_response.get());
410
411 patchpanel::ArcStartupRequest request;
412 patchpanel::ArcStartupResponse response;
413
414 if (!reader.PopArrayOfBytesAsProto(&request)) {
415 LOG(ERROR) << "Unable to parse request";
416 writer.AppendProtoAsArrayOfBytes(response);
417 return dbus_response;
418 }
419
Garrick Evanse01bf072019-11-15 09:08:19 +0900420 if (!StartArc(request.pid()))
421 LOG(ERROR) << "Failed to start ARC++ network service";
Garrick Evanse94a14e2019-11-11 10:32:13 +0900422
Garrick Evans08843932019-09-17 14:41:08 +0900423 writer.AppendProtoAsArrayOfBytes(response);
424 return dbus_response;
425}
426
427std::unique_ptr<dbus::Response> Manager::OnArcShutdown(
428 dbus::MethodCall* method_call) {
429 LOG(INFO) << "ARC++ shutting down";
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::ArcShutdownRequest request;
438 patchpanel::ArcShutdownResponse 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 Evans21173b12019-11-20 15:23:16 +0900446 StopArc(request.pid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900447
Garrick Evans08843932019-09-17 14:41:08 +0900448 writer.AppendProtoAsArrayOfBytes(response);
449 return dbus_response;
450}
451
452std::unique_ptr<dbus::Response> Manager::OnArcVmStartup(
453 dbus::MethodCall* method_call) {
454 LOG(INFO) << "ARCVM starting up";
455
456 std::unique_ptr<dbus::Response> dbus_response(
457 dbus::Response::FromMethodCall(method_call));
458
459 dbus::MessageReader reader(method_call);
460 dbus::MessageWriter writer(dbus_response.get());
461
462 patchpanel::ArcVmStartupRequest request;
463 patchpanel::ArcVmStartupResponse response;
464
465 if (!reader.PopArrayOfBytesAsProto(&request)) {
466 LOG(ERROR) << "Unable to parse request";
467 writer.AppendProtoAsArrayOfBytes(response);
468 return dbus_response;
469 }
470
Garrick Evans47c19272019-11-21 10:58:21 +0900471 if (!StartArcVm(request.cid())) {
Garrick Evanse01bf072019-11-15 09:08:19 +0900472 LOG(ERROR) << "Failed to start ARCVM network service";
Garrick Evans47c19272019-11-21 10:58:21 +0900473 writer.AppendProtoAsArrayOfBytes(response);
474 return dbus_response;
Garrick Evanse01bf072019-11-15 09:08:19 +0900475 }
Garrick Evanse94a14e2019-11-11 10:32:13 +0900476
Garrick Evans47c19272019-11-21 10:58:21 +0900477 // Populate the response with the known devices.
Garrick Evans38b25a42020-04-06 15:17:42 +0900478 for (const auto* config : arc_svc_->GetDeviceConfigs()) {
479 if (config->tap_ifname().empty())
480 continue;
Garrick Evans47c19272019-11-21 10:58:21 +0900481
Garrick Evans38b25a42020-04-06 15:17:42 +0900482 auto* dev = response.add_devices();
483 dev->set_ifname(config->tap_ifname());
484 dev->set_ipv4_addr(config->guest_ipv4_addr());
485 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900486
Garrick Evans08843932019-09-17 14:41:08 +0900487 writer.AppendProtoAsArrayOfBytes(response);
488 return dbus_response;
489}
490
491std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
492 dbus::MethodCall* method_call) {
493 LOG(INFO) << "ARCVM shutting down";
494
495 std::unique_ptr<dbus::Response> dbus_response(
496 dbus::Response::FromMethodCall(method_call));
497
498 dbus::MessageReader reader(method_call);
499 dbus::MessageWriter writer(dbus_response.get());
500
501 patchpanel::ArcVmShutdownRequest request;
502 patchpanel::ArcVmShutdownResponse response;
503
504 if (!reader.PopArrayOfBytesAsProto(&request)) {
505 LOG(ERROR) << "Unable to parse request";
506 writer.AppendProtoAsArrayOfBytes(response);
507 return dbus_response;
508 }
509
Garrick Evans21173b12019-11-20 15:23:16 +0900510 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900511
Garrick Evans08843932019-09-17 14:41:08 +0900512 writer.AppendProtoAsArrayOfBytes(response);
513 return dbus_response;
514}
515
Garrick Evans47c19272019-11-21 10:58:21 +0900516std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
517 dbus::MethodCall* method_call) {
518 LOG(INFO) << "Termina VM starting up";
519
520 std::unique_ptr<dbus::Response> dbus_response(
521 dbus::Response::FromMethodCall(method_call));
522
523 dbus::MessageReader reader(method_call);
524 dbus::MessageWriter writer(dbus_response.get());
525
526 patchpanel::TerminaVmStartupRequest request;
527 patchpanel::TerminaVmStartupResponse response;
528
529 if (!reader.PopArrayOfBytesAsProto(&request)) {
530 LOG(ERROR) << "Unable to parse request";
531 writer.AppendProtoAsArrayOfBytes(response);
532 return dbus_response;
533 }
534
535 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900536 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900537 LOG(ERROR) << "Failed to start Termina VM network service";
538 writer.AppendProtoAsArrayOfBytes(response);
539 return dbus_response;
540 }
541
Garrick Evans51d5b552020-01-30 10:42:06 +0900542 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900543 if (!tap) {
544 LOG(DFATAL) << "TAP device missing";
545 writer.AppendProtoAsArrayOfBytes(response);
546 return dbus_response;
547 }
Garrick Evans47c19272019-11-21 10:58:21 +0900548
Garrick Evansb1c93712020-01-22 09:28:25 +0900549 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900550 dev->set_ifname(tap->host_ifname());
551 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900552 if (!subnet) {
553 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
554 writer.AppendProtoAsArrayOfBytes(response);
555 return dbus_response;
556 }
557 auto* resp_subnet = dev->mutable_ipv4_subnet();
558 resp_subnet->set_base_addr(subnet->BaseAddress());
559 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900560 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900561 if (!subnet) {
562 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
563 writer.AppendProtoAsArrayOfBytes(response);
564 return dbus_response;
565 }
566 resp_subnet = response.mutable_container_subnet();
567 resp_subnet->set_base_addr(subnet->BaseAddress());
568 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900569
570 writer.AppendProtoAsArrayOfBytes(response);
571 return dbus_response;
572}
573
574std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
575 dbus::MethodCall* method_call) {
576 LOG(INFO) << "Termina VM shutting down";
577
578 std::unique_ptr<dbus::Response> dbus_response(
579 dbus::Response::FromMethodCall(method_call));
580
581 dbus::MessageReader reader(method_call);
582 dbus::MessageWriter writer(dbus_response.get());
583
584 patchpanel::TerminaVmShutdownRequest request;
585 patchpanel::TerminaVmShutdownResponse response;
586
587 if (!reader.PopArrayOfBytesAsProto(&request)) {
588 LOG(ERROR) << "Unable to parse request";
589 writer.AppendProtoAsArrayOfBytes(response);
590 return dbus_response;
591 }
592
Garrick Evans51d5b552020-01-30 10:42:06 +0900593 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
594
595 writer.AppendProtoAsArrayOfBytes(response);
596 return dbus_response;
597}
598
599std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
600 dbus::MethodCall* method_call) {
601 LOG(INFO) << "Plugin VM starting up";
602
603 std::unique_ptr<dbus::Response> dbus_response(
604 dbus::Response::FromMethodCall(method_call));
605
606 dbus::MessageReader reader(method_call);
607 dbus::MessageWriter writer(dbus_response.get());
608
609 patchpanel::PluginVmStartupRequest request;
610 patchpanel::PluginVmStartupResponse response;
611
612 if (!reader.PopArrayOfBytesAsProto(&request)) {
613 LOG(ERROR) << "Unable to parse request";
614 writer.AppendProtoAsArrayOfBytes(response);
615 return dbus_response;
616 }
617
Garrick Evans08fb34b2020-02-20 10:50:17 +0900618 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900619 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900620 LOG(ERROR) << "Failed to start Plugin VM network service";
621 writer.AppendProtoAsArrayOfBytes(response);
622 return dbus_response;
623 }
624
625 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
626 if (!tap) {
627 LOG(DFATAL) << "TAP device missing";
628 writer.AppendProtoAsArrayOfBytes(response);
629 return dbus_response;
630 }
631
Garrick Evans51d5b552020-01-30 10:42:06 +0900632 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900633 dev->set_ifname(tap->host_ifname());
634 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900635 if (!subnet) {
636 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
637 writer.AppendProtoAsArrayOfBytes(response);
638 return dbus_response;
639 }
640 auto* resp_subnet = dev->mutable_ipv4_subnet();
641 resp_subnet->set_base_addr(subnet->BaseAddress());
642 resp_subnet->set_prefix_len(subnet->PrefixLength());
643
644 writer.AppendProtoAsArrayOfBytes(response);
645 return dbus_response;
646}
647
648std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
649 dbus::MethodCall* method_call) {
650 LOG(INFO) << "Plugin VM shutting down";
651
652 std::unique_ptr<dbus::Response> dbus_response(
653 dbus::Response::FromMethodCall(method_call));
654
655 dbus::MessageReader reader(method_call);
656 dbus::MessageWriter writer(dbus_response.get());
657
658 patchpanel::PluginVmShutdownRequest request;
659 patchpanel::PluginVmShutdownResponse response;
660
661 if (!reader.PopArrayOfBytesAsProto(&request)) {
662 LOG(ERROR) << "Unable to parse request";
663 writer.AppendProtoAsArrayOfBytes(response);
664 return dbus_response;
665 }
666
667 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900668
669 writer.AppendProtoAsArrayOfBytes(response);
670 return dbus_response;
671}
672
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900673std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
674 dbus::MethodCall* method_call) {
675 std::unique_ptr<dbus::Response> dbus_response(
676 dbus::Response::FromMethodCall(method_call));
677
678 dbus::MessageReader reader(method_call);
679 dbus::MessageWriter writer(dbus_response.get());
680
681 patchpanel::SetVpnIntentRequest request;
682 patchpanel::SetVpnIntentResponse response;
683
684 bool success = reader.PopArrayOfBytesAsProto(&request);
685 if (!success) {
686 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
687 // Do not return yet to make sure we close the received fd.
688 }
689
690 base::ScopedFD client_socket;
691 reader.PopFileDescriptor(&client_socket);
692
693 if (success)
694 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
695
696 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900697
698 writer.AppendProtoAsArrayOfBytes(response);
699 return dbus_response;
700}
701
702std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
703 dbus::MethodCall* method_call) {
704 std::unique_ptr<dbus::Response> dbus_response(
705 dbus::Response::FromMethodCall(method_call));
706
707 dbus::MessageReader reader(method_call);
708 dbus::MessageWriter writer(dbus_response.get());
709
710 patchpanel::ConnectNamespaceRequest request;
711 patchpanel::ConnectNamespaceResponse response;
712
Hugo Benichicc6850f2020-01-17 13:26:06 +0900713 bool success = true;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900714 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900715 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
716 // Do not return yet to make sure we close the received fd and
717 // validate other arguments.
718 success = false;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900719 }
720
Hugo Benichicc6850f2020-01-17 13:26:06 +0900721 base::ScopedFD client_fd;
722 reader.PopFileDescriptor(&client_fd);
723 if (!client_fd.is_valid()) {
724 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
725 success = false;
726 }
727
728 pid_t pid = request.pid();
729 {
730 ScopedNS ns(pid);
731 if (!ns.IsValid()) {
732 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
733 success = false;
734 }
735 }
736
737 const std::string& outbound_ifname = request.outbound_physical_device();
738 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
739 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
740 << outbound_ifname;
741 success = false;
742 }
743
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900744 if (success)
745 ConnectNamespace(std::move(client_fd), request, response);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900746
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900747 writer.AppendProtoAsArrayOfBytes(response);
748 return dbus_response;
749}
750
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900751void Manager::ConnectNamespace(
752 base::ScopedFD client_fd,
753 const patchpanel::ConnectNamespaceRequest& request,
754 patchpanel::ConnectNamespaceResponse& response) {
755 std::unique_ptr<Subnet> subnet =
756 addr_mgr_.AllocateIPv4Subnet(AddressManager::Guest::MINIJAIL_NETNS);
757 if (!subnet) {
758 LOG(ERROR) << "ConnectNamespaceRequest: exhausted IPv4 subnet space";
759 return;
760 }
761
762 const std::string ifname_id = std::to_string(connected_namespaces_next_id_);
763 const std::string host_ifname = "arc_ns" + ifname_id;
764 const std::string client_ifname = "veth" + ifname_id;
Hugo Benichie8758b52020-04-03 14:49:01 +0900765 const uint32_t host_ipv4_addr = subnet->AddressAtOffset(0);
766 const uint32_t client_ipv4_addr = subnet->AddressAtOffset(1);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900767
Hugo Benichie8758b52020-04-03 14:49:01 +0900768 // Veth interface configuration and client routing configuration:
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900769 // - create veth pair inside client namespace.
770 // - configure IPv4 address on remote veth inside client namespace.
Hugo Benichie8758b52020-04-03 14:49:01 +0900771 // - configure IPv4 address on local veth inside host namespace.
772 // - add a default IPv4 /0 route sending traffic to that remote veth.
773 // - bring back one veth to the host namespace, and set it up.
774 pid_t pid = request.pid();
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900775 if (!datapath_->ConnectVethPair(pid, host_ifname, client_ifname,
776 addr_mgr_.GenerateMacAddress(),
777 client_ipv4_addr, subnet->PrefixLength(),
778 false /* enable_multicast */)) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900779 LOG(ERROR) << "ConnectNamespaceRequest: failed to create veth pair for "
780 "namespace pid "
781 << pid;
782 return;
783 }
784 if (!datapath_->ConfigureInterface(
785 host_ifname, addr_mgr_.GenerateMacAddress(), host_ipv4_addr,
786 subnet->PrefixLength(), true /* link up */,
787 false /* enable_multicast */)) {
788 LOG(ERROR) << "ConnectNamespaceRequest: cannot configure host interface "
789 << host_ifname;
790 datapath_->RemoveInterface(host_ifname);
791 return;
792 }
793 {
794 ScopedNS ns(pid);
795 if (!ns.IsValid()) {
796 LOG(ERROR) << "ConnectNamespaceRequest: cannot enter client pid " << pid;
797 datapath_->RemoveInterface(host_ifname);
798 return;
799 }
800 if (!datapath_->AddIPv4Route(host_ipv4_addr, INADDR_ANY, INADDR_ANY)) {
801 LOG(ERROR)
802 << "ConnectNamespaceRequest: failed to add default /0 route to "
803 << host_ifname << " inside namespace pid " << pid;
804 datapath_->RemoveInterface(host_ifname);
805 return;
806 }
807 }
808
809 // Host namespace routing configuration
810 // - ingress: add route to client subnet via |host_ifname|.
811 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
812 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
813 // Note that by default unsolicited ingress traffic is not forwarded to the
814 // client namespace unless the client specifically set port forwarding
815 // through permission_broker DBus APIs.
816 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
817 // both ways between client namespace and other guest containers and VMs.
818 // TODO(hugobenichi) If outbound_physical_device is defined, then set strong
819 // routing to that interface routing table.
820 if (!datapath_->AddIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
821 subnet->Netmask())) {
822 LOG(ERROR)
823 << "ConnectNamespaceRequest: failed to set route to client namespace";
824 datapath_->RemoveInterface(host_ifname);
825 return;
826 }
827 if (!datapath_->AddOutboundIPv4(host_ifname)) {
828 LOG(ERROR) << "ConnectNamespaceRequest: failed to allow FORWARD for "
829 "traffic outgoing from "
830 << host_ifname;
831 datapath_->RemoveInterface(host_ifname);
832 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
833 subnet->Netmask());
834 return;
835 }
836 if (!datapath_->AddOutboundIPv4SNATMark(host_ifname)) {
837 LOG(ERROR) << "ConnectNamespaceRequest: failed to set SNAT for traffic "
838 "outgoing from "
839 << host_ifname;
840 datapath_->RemoveInterface(host_ifname);
841 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
842 subnet->Netmask());
843 datapath_->RemoveOutboundIPv4(host_ifname);
844 return;
845 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900846
Hugo Benichi7352ad92020-04-07 16:11:59 +0900847 // Dup the client fd into our own: this guarantees that the fd number will
848 // be stable and tied to the actual kernel resources used by the client.
849 base::ScopedFD local_client_fd(dup(client_fd.get()));
850 if (!local_client_fd.is_valid()) {
851 PLOG(ERROR) << "ConnectNamespaceRequest: failed to dup() client fd";
Hugo Benichie8758b52020-04-03 14:49:01 +0900852 datapath_->RemoveInterface(host_ifname);
853 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
854 subnet->Netmask());
855 datapath_->RemoveOutboundIPv4(host_ifname);
856 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900857 return;
858 }
859
860 // Add the dupe fd to the epoll watcher.
861 // TODO(hugobenichi) Find a way to reuse base::FileDescriptorWatcher for
862 // listening to EPOLLHUP.
863 struct epoll_event epevent;
864 epevent.events = EPOLLIN; // EPOLLERR | EPOLLHUP are always waited for.
865 epevent.data.fd = local_client_fd.get();
866 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_ADD,
867 local_client_fd.get(), &epevent) != 0) {
868 PLOG(ERROR) << "ConnectNamespaceResponse: epoll_ctl(EPOLL_CTL_ADD) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900869 datapath_->RemoveInterface(host_ifname);
870 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
871 subnet->Netmask());
872 datapath_->RemoveOutboundIPv4(host_ifname);
873 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900874 return;
875 }
876
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900877 // Prepare the response before storing ConnectNamespaceInfo.
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900878 response.set_peer_ifname(client_ifname);
879 response.set_peer_ipv4_address(host_ipv4_addr);
880 response.set_host_ifname(host_ifname);
881 response.set_host_ipv4_address(client_ipv4_addr);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900882 auto* response_subnet = response.mutable_ipv4_subnet();
883 response_subnet->set_base_addr(subnet->BaseAddress());
884 response_subnet->set_prefix_len(subnet->PrefixLength());
885
886 // Store ConnectNamespaceInfo
887 connected_namespaces_next_id_++;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900888 int fdkey = local_client_fd.release();
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900889 connected_namespaces_[fdkey] = {};
890 ConnectNamespaceInfo& ns_info = connected_namespaces_[fdkey];
891 ns_info.pid = request.pid();
892 ns_info.outbound_ifname = request.outbound_physical_device();
893 ns_info.host_ifname = std::move(host_ifname);
894 ns_info.client_ifname = std::move(client_ifname);
895 ns_info.client_subnet = std::move(subnet);
896
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900897 LOG(INFO) << "Connected network namespace " << ns_info;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900898
899 if (connected_namespaces_.size() == 1) {
900 LOG(INFO) << "Starting ConnectNamespace client fds monitoring";
901 CheckConnectedNamespaces();
902 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900903}
904
905void Manager::DisconnectNamespace(int client_fd) {
906 auto it = connected_namespaces_.find(client_fd);
907 if (it == connected_namespaces_.end()) {
908 LOG(ERROR) << "No ConnectNamespaceInfo found for client_fd " << client_fd;
909 return;
910 }
911
Hugo Benichi7352ad92020-04-07 16:11:59 +0900912 // Remove the client fd dupe from the epoll watcher and close it.
913 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL, client_fd,
Hugo Benichie8758b52020-04-03 14:49:01 +0900914 nullptr) != 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900915 PLOG(ERROR) << "DisconnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900916 if (close(client_fd) < 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900917 PLOG(ERROR) << "DisconnectNamespace: close(client_fd) failed";
Hugo Benichi7352ad92020-04-07 16:11:59 +0900918
Hugo Benichie8758b52020-04-03 14:49:01 +0900919 // Destroy the interface configuration and routing configuration:
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900920 // - destroy veth pair.
Hugo Benichie8758b52020-04-03 14:49:01 +0900921 // - remove forwarding rules on host namespace.
922 // - remove SNAT marking rule on host namespace.
923 // Note that the default route set inside the client namespace by patchpanel
924 // is not destroyed: it is assumed the client will also teardown its
925 // namespace if it triggered DisconnectNamespace.
926 datapath_->RemoveInterface(it->second.host_ifname);
927 datapath_->RemoveOutboundIPv4(it->second.host_ifname);
928 datapath_->RemoveOutboundIPv4SNATMark(it->second.host_ifname);
929 datapath_->DeleteIPv4Route(it->second.client_subnet->AddressAtOffset(0),
930 it->second.client_subnet->BaseAddress(),
931 it->second.client_subnet->Netmask());
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900932
933 LOG(INFO) << "Disconnected network namespace " << it->second;
934
935 // This release the allocated IPv4 subnet.
936 connected_namespaces_.erase(it);
937}
938
Hugo Benichi7352ad92020-04-07 16:11:59 +0900939// TODO(hugobenichi) Generalize this check to all resources created by
940// patchpanel on behalf of a remote client.
941void Manager::CheckConnectedNamespaces() {
942 int max_event = 10;
943 struct epoll_event epevents[max_event];
944 int nready = epoll_wait(connected_namespaces_epollfd_, epevents, max_event,
945 0 /* do not block */);
946 if (nready < 0)
947 PLOG(ERROR) << "CheckConnectedNamespaces: epoll_wait(0) failed";
948
949 for (int i = 0; i < nready; i++)
950 if (epevents[i].events & (EPOLLHUP | EPOLLERR))
951 DisconnectNamespace(epevents[i].data.fd);
952
953 if (connected_namespaces_.empty()) {
954 LOG(INFO) << "Stopping ConnectNamespace client fds monitoring";
955 return;
956 }
957
Qijiang Fan2d7aeb42020-05-19 02:06:39 +0900958 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Hugo Benichi7352ad92020-04-07 16:11:59 +0900959 FROM_HERE,
960 base::Bind(&Manager::CheckConnectedNamespaces,
Hugo Benichie8758b52020-04-03 14:49:01 +0900961 weak_factory_.GetWeakPtr()),
Hugo Benichi7352ad92020-04-07 16:11:59 +0900962 kConnectNamespaceCheckInterval);
963}
964
Garrick Evanse94a14e2019-11-11 10:32:13 +0900965void Manager::SendGuestMessage(const GuestMessage& msg) {
Garrick Evans96e03042019-05-28 14:30:52 +0900966 IpHelperMessage ipm;
967 *ipm.mutable_guest_message() = msg;
Garrick Evans96e03042019-05-28 14:30:52 +0900968 adb_proxy_->SendMessage(ipm);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900969 mcast_proxy_->SendMessage(ipm);
970 nd_proxy_->SendMessage(ipm);
Garrick Evans96e03042019-05-28 14:30:52 +0900971}
972
Garrick Evans4ac09852020-01-16 14:09:22 +0900973void Manager::StartForwarding(const std::string& ifname_physical,
974 const std::string& ifname_virtual,
Garrick Evans4ac09852020-01-16 14:09:22 +0900975 bool ipv6,
976 bool multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +0900977 if (ifname_physical.empty() || ifname_virtual.empty())
Garrick Evans4ac09852020-01-16 14:09:22 +0900978 return;
979
980 IpHelperMessage ipm;
981 DeviceMessage* msg = ipm.mutable_device_message();
982 msg->set_dev_ifname(ifname_physical);
Garrick Evans4ac09852020-01-16 14:09:22 +0900983 msg->set_br_ifname(ifname_virtual);
984
985 if (ipv6) {
986 LOG(INFO) << "Starting IPv6 forwarding from " << ifname_physical << " to "
987 << ifname_virtual;
988
989 if (!datapath_->AddIPv6Forwarding(ifname_physical, ifname_virtual)) {
990 LOG(ERROR) << "Failed to setup iptables forwarding rule for IPv6 from "
991 << ifname_physical << " to " << ifname_virtual;
992 }
993 if (!datapath_->MaskInterfaceFlags(ifname_physical, IFF_ALLMULTI)) {
994 LOG(WARNING) << "Failed to setup all multicast mode for interface "
995 << ifname_physical;
996 }
997 if (!datapath_->MaskInterfaceFlags(ifname_virtual, IFF_ALLMULTI)) {
998 LOG(WARNING) << "Failed to setup all multicast mode for interface "
999 << ifname_virtual;
1000 }
1001 nd_proxy_->SendMessage(ipm);
1002 }
1003
1004 if (multicast) {
1005 LOG(INFO) << "Starting multicast forwarding from " << ifname_physical
1006 << " to " << ifname_virtual;
1007 mcast_proxy_->SendMessage(ipm);
1008 }
1009}
1010
1011void Manager::StopForwarding(const std::string& ifname_physical,
1012 const std::string& ifname_virtual,
1013 bool ipv6,
1014 bool multicast) {
1015 if (ifname_physical.empty())
1016 return;
1017
1018 IpHelperMessage ipm;
1019 DeviceMessage* msg = ipm.mutable_device_message();
1020 msg->set_dev_ifname(ifname_physical);
1021 msg->set_teardown(true);
Taoyu Li7dca19a2020-03-16 16:27:07 +09001022 if (!ifname_virtual.empty()) {
1023 msg->set_br_ifname(ifname_virtual);
1024 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001025
1026 if (ipv6) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001027 if (ifname_virtual.empty()) {
1028 LOG(INFO) << "Stopping IPv6 forwarding on " << ifname_physical;
1029 } else {
1030 LOG(INFO) << "Stopping IPv6 forwarding from " << ifname_physical << " to "
1031 << ifname_virtual;
1032 datapath_->RemoveIPv6Forwarding(ifname_physical, ifname_virtual);
1033 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001034 nd_proxy_->SendMessage(ipm);
1035 }
1036
1037 if (multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001038 if (ifname_virtual.empty()) {
1039 LOG(INFO) << "Stopping multicast forwarding on " << ifname_physical;
1040 } else {
1041 LOG(INFO) << "Stopping multicast forwarding from " << ifname_physical
1042 << " to " << ifname_virtual;
1043 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001044 mcast_proxy_->SendMessage(ipm);
1045 }
1046}
1047
Garrick Evans4ac09852020-01-16 14:09:22 +09001048void Manager::OnDeviceMessageFromNDProxy(const DeviceMessage& msg) {
1049 LOG_IF(DFATAL, msg.dev_ifname().empty())
1050 << "Received DeviceMessage w/ empty dev_ifname";
1051
1052 if (!datapath_->AddIPv6HostRoute(msg.dev_ifname(), msg.guest_ip6addr(),
1053 128)) {
1054 LOG(WARNING) << "Failed to setup the IPv6 route for interface "
1055 << msg.dev_ifname();
1056 }
1057}
1058
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001059std::ostream& operator<<(std::ostream& stream,
1060 const Manager::ConnectNamespaceInfo& ns_info) {
1061 stream << "{ pid: " << ns_info.pid;
1062 if (!ns_info.outbound_ifname.empty()) {
1063 stream << ", outbound_ifname: " << ns_info.outbound_ifname;
1064 }
1065 stream << ", host_ifname: " << ns_info.host_ifname
1066 << ", client_ifname: " << ns_info.client_ifname
1067 << ", subnet: " << ns_info.client_subnet->ToCidrString() << '}';
1068 return stream;
1069}
1070
Garrick Evans3388a032020-03-24 11:25:55 +09001071} // namespace patchpanel