blob: 217e90936ca6911aabe255574e25f5e79e72056e [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 Evans28d194e2019-12-17 10:22:28 +0900222 // Limit local port range: Android owns 47104-61000.
223 // TODO(garrick): The original history behind this tweak is gone. Some
224 // investigation is needed to see if it is still applicable.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900225 if (runner.sysctl_w("net.ipv4.ip_local_port_range", "32768 47103") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900226 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
227 << " apps may not work correctly.";
228 }
Taoyu Li6d479442019-12-09 13:02:29 +0900229 // Enable IPv6 packet forarding
Garrick Evans8e8e3472020-01-23 14:03:50 +0900230 if (runner.sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0) {
Taoyu Li6d479442019-12-09 13:02:29 +0900231 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
232 << " IPv6 functionality may be broken.";
233 }
234 // Kernel proxy_ndp is only needed for legacy IPv6 configuration
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +0900235 if (!ShouldEnableFeature(kNDProxyMinAndroidSdkVersion,
Garrick Evansf5862122020-03-16 09:13:45 +0900236 kNDProxyMinChromeMilestone, {},
237 kNDProxyFeatureName) &&
Garrick Evans8e8e3472020-01-23 14:03:50 +0900238 runner.sysctl_w("net.ipv6.conf.all.proxy_ndp", "1") != 0) {
Taoyu Li6d479442019-12-09 13:02:29 +0900239 LOG(ERROR) << "Failed to update net.ipv6.conf.all.proxy_ndp."
240 << " IPv6 functionality may be broken.";
241 }
242
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900243 routing_svc_ = std::make_unique<RoutingService>();
244
Garrick Evans4ac09852020-01-16 14:09:22 +0900245 nd_proxy_->RegisterDeviceMessageHandler(base::Bind(
246 &Manager::OnDeviceMessageFromNDProxy, weak_factory_.GetWeakPtr()));
247
Garrick Evans69b85872020-02-04 11:40:26 +0900248 shill_client_ = std::make_unique<ShillClient>(bus_);
Garrick Evans1b1f67c2020-02-04 16:21:25 +0900249 auto* const forwarder = static_cast<TrafficForwarder*>(this);
Garrick Evans5d55f5e2019-07-17 15:28:10 +0900250
Garrick Evansf5862122020-03-16 09:13:45 +0900251 arc_svc_ = std::make_unique<ArcService>(
252 shill_client_.get(), datapath_.get(), &addr_mgr_, forwarder,
253 ShouldEnableFeature(kArcVmMultinetMinAndroidSdkVersion,
254 kArcVmMultinetMinChromeMilestone, {},
255 kArcVmMultinetFeatureName));
Garrick Evans1b1f67c2020-02-04 16:21:25 +0900256 cros_svc_ = std::make_unique<CrostiniService>(shill_client_.get(), &addr_mgr_,
257 datapath_.get(), forwarder);
Taoyu Liaf944c92019-10-01 12:22:31 +0900258
259 nd_proxy_->Listen();
Long Chengd4415582019-09-24 19:16:09 +0000260}
Garrick Evans49879532018-12-03 13:15:36 +0900261
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800262void Manager::OnShutdown(int* exit_code) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900263 LOG(INFO) << "Shutting down and cleaning up";
Garrick Evans207e7482019-12-16 11:54:36 +0900264 cros_svc_.reset();
265 arc_svc_.reset();
Hugo Benichi7352ad92020-04-07 16:11:59 +0900266 close(connected_namespaces_epollfd_);
Hugo Benichie8758b52020-04-03 14:49:01 +0900267 // Tear down any remaining connected namespace.
268 std::vector<int> connected_namespaces_fdkeys;
269 for (const auto& kv : connected_namespaces_)
270 connected_namespaces_fdkeys.push_back(kv.first);
271 for (const int fdkey : connected_namespaces_fdkeys)
272 DisconnectNamespace(fdkey);
Garrick Evans28d194e2019-12-17 10:22:28 +0900273
274 // Restore original local port range.
275 // TODO(garrick): The original history behind this tweak is gone. Some
276 // investigation is needed to see if it is still applicable.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900277 if (datapath_->runner().sysctl_w("net.ipv4.ip_local_port_range",
278 "32768 61000") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900279 LOG(ERROR) << "Failed to restore local port range";
280 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800281}
282
Garrick Evans4c042572019-12-17 13:42:25 +0900283void Manager::OnSubprocessExited(pid_t pid, const siginfo_t&) {
284 LOG(ERROR) << "Subprocess " << pid << " exited unexpectedly -"
285 << " attempting to restart";
286
287 HelperProcess* proc;
288 if (pid == adb_proxy_->pid()) {
289 proc = adb_proxy_.get();
290 } else if (pid == mcast_proxy_->pid()) {
291 proc = mcast_proxy_.get();
292 } else if (pid == nd_proxy_->pid()) {
293 proc = nd_proxy_.get();
294 } else {
295 LOG(DFATAL) << "Unknown child process";
296 return;
297 }
298
299 process_reaper_.ForgetChild(pid);
300
hschamf9546312020-04-14 15:12:40 +0900301 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Garrick Evans4c042572019-12-17 13:42:25 +0900302 FROM_HERE,
303 base::Bind(&Manager::RestartSubprocess, weak_factory_.GetWeakPtr(), proc),
304 base::TimeDelta::FromMilliseconds((2 << proc->restarts()) *
305 kSubprocessRestartDelayMs));
306}
307
308void Manager::RestartSubprocess(HelperProcess* subproc) {
309 if (subproc->Restart()) {
310 DCHECK(process_reaper_.WatchForChild(
311 FROM_HERE, subproc->pid(),
312 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
313 subproc->pid())))
314 << "Failed to watch child process " << subproc->pid();
315 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800316}
317
Garrick Evanse94a14e2019-11-11 10:32:13 +0900318bool Manager::StartArc(pid_t pid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900319 if (!arc_svc_->Start(pid))
320 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900321
322 GuestMessage msg;
323 msg.set_event(GuestMessage::START);
324 msg.set_type(GuestMessage::ARC);
325 msg.set_arc_pid(pid);
326 SendGuestMessage(msg);
327
328 return true;
329}
330
Garrick Evans21173b12019-11-20 15:23:16 +0900331void Manager::StopArc(pid_t pid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900332 GuestMessage msg;
333 msg.set_event(GuestMessage::STOP);
334 msg.set_type(GuestMessage::ARC);
335 SendGuestMessage(msg);
336
Garrick Evans21173b12019-11-20 15:23:16 +0900337 arc_svc_->Stop(pid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900338}
339
Garrick Evans015b0d62020-02-07 09:06:38 +0900340bool Manager::StartArcVm(uint32_t cid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900341 if (!arc_svc_->Start(cid))
342 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900343
344 GuestMessage msg;
345 msg.set_event(GuestMessage::START);
346 msg.set_type(GuestMessage::ARC_VM);
347 msg.set_arcvm_vsock_cid(cid);
348 SendGuestMessage(msg);
349
350 return true;
351}
352
Garrick Evans015b0d62020-02-07 09:06:38 +0900353void Manager::StopArcVm(uint32_t cid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900354 GuestMessage msg;
355 msg.set_event(GuestMessage::STOP);
356 msg.set_type(GuestMessage::ARC_VM);
357 SendGuestMessage(msg);
358
Garrick Evans21173b12019-11-20 15:23:16 +0900359 arc_svc_->Stop(cid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900360}
361
Garrick Evans51d5b552020-01-30 10:42:06 +0900362bool Manager::StartCrosVm(uint64_t vm_id,
363 GuestMessage::GuestType vm_type,
Garrick Evans53a2a982020-02-05 10:53:35 +0900364 uint32_t subnet_index) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900365 DCHECK(vm_type == GuestMessage::TERMINA_VM ||
366 vm_type == GuestMessage::PLUGIN_VM);
367
368 if (!cros_svc_->Start(vm_id, vm_type == GuestMessage::TERMINA_VM,
369 subnet_index))
Garrick Evans47c19272019-11-21 10:58:21 +0900370 return false;
371
372 GuestMessage msg;
373 msg.set_event(GuestMessage::START);
Garrick Evans51d5b552020-01-30 10:42:06 +0900374 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900375 SendGuestMessage(msg);
376
377 return true;
378}
379
Garrick Evans51d5b552020-01-30 10:42:06 +0900380void Manager::StopCrosVm(uint64_t vm_id, GuestMessage::GuestType vm_type) {
Garrick Evans47c19272019-11-21 10:58:21 +0900381 GuestMessage msg;
382 msg.set_event(GuestMessage::STOP);
Garrick Evans51d5b552020-01-30 10:42:06 +0900383 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900384 SendGuestMessage(msg);
385
Garrick Evans51d5b552020-01-30 10:42:06 +0900386 cros_svc_->Stop(vm_id, vm_type == GuestMessage::TERMINA_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900387}
388
Garrick Evans08843932019-09-17 14:41:08 +0900389std::unique_ptr<dbus::Response> Manager::OnArcStartup(
390 dbus::MethodCall* method_call) {
391 LOG(INFO) << "ARC++ starting up";
392
393 std::unique_ptr<dbus::Response> dbus_response(
394 dbus::Response::FromMethodCall(method_call));
395
396 dbus::MessageReader reader(method_call);
397 dbus::MessageWriter writer(dbus_response.get());
398
399 patchpanel::ArcStartupRequest request;
400 patchpanel::ArcStartupResponse response;
401
402 if (!reader.PopArrayOfBytesAsProto(&request)) {
403 LOG(ERROR) << "Unable to parse request";
404 writer.AppendProtoAsArrayOfBytes(response);
405 return dbus_response;
406 }
407
Garrick Evanse01bf072019-11-15 09:08:19 +0900408 if (!StartArc(request.pid()))
409 LOG(ERROR) << "Failed to start ARC++ network service";
Garrick Evanse94a14e2019-11-11 10:32:13 +0900410
Garrick Evans08843932019-09-17 14:41:08 +0900411 writer.AppendProtoAsArrayOfBytes(response);
412 return dbus_response;
413}
414
415std::unique_ptr<dbus::Response> Manager::OnArcShutdown(
416 dbus::MethodCall* method_call) {
417 LOG(INFO) << "ARC++ shutting down";
418
419 std::unique_ptr<dbus::Response> dbus_response(
420 dbus::Response::FromMethodCall(method_call));
421
422 dbus::MessageReader reader(method_call);
423 dbus::MessageWriter writer(dbus_response.get());
424
425 patchpanel::ArcShutdownRequest request;
426 patchpanel::ArcShutdownResponse response;
427
428 if (!reader.PopArrayOfBytesAsProto(&request)) {
429 LOG(ERROR) << "Unable to parse request";
430 writer.AppendProtoAsArrayOfBytes(response);
431 return dbus_response;
432 }
433
Garrick Evans21173b12019-11-20 15:23:16 +0900434 StopArc(request.pid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900435
Garrick Evans08843932019-09-17 14:41:08 +0900436 writer.AppendProtoAsArrayOfBytes(response);
437 return dbus_response;
438}
439
440std::unique_ptr<dbus::Response> Manager::OnArcVmStartup(
441 dbus::MethodCall* method_call) {
442 LOG(INFO) << "ARCVM starting up";
443
444 std::unique_ptr<dbus::Response> dbus_response(
445 dbus::Response::FromMethodCall(method_call));
446
447 dbus::MessageReader reader(method_call);
448 dbus::MessageWriter writer(dbus_response.get());
449
450 patchpanel::ArcVmStartupRequest request;
451 patchpanel::ArcVmStartupResponse response;
452
453 if (!reader.PopArrayOfBytesAsProto(&request)) {
454 LOG(ERROR) << "Unable to parse request";
455 writer.AppendProtoAsArrayOfBytes(response);
456 return dbus_response;
457 }
458
Garrick Evans47c19272019-11-21 10:58:21 +0900459 if (!StartArcVm(request.cid())) {
Garrick Evanse01bf072019-11-15 09:08:19 +0900460 LOG(ERROR) << "Failed to start ARCVM network service";
Garrick Evans47c19272019-11-21 10:58:21 +0900461 writer.AppendProtoAsArrayOfBytes(response);
462 return dbus_response;
Garrick Evanse01bf072019-11-15 09:08:19 +0900463 }
Garrick Evanse94a14e2019-11-11 10:32:13 +0900464
Garrick Evans47c19272019-11-21 10:58:21 +0900465 // Populate the response with the known devices.
Garrick Evans38b25a42020-04-06 15:17:42 +0900466 for (const auto* config : arc_svc_->GetDeviceConfigs()) {
467 if (config->tap_ifname().empty())
468 continue;
Garrick Evans47c19272019-11-21 10:58:21 +0900469
Garrick Evans38b25a42020-04-06 15:17:42 +0900470 auto* dev = response.add_devices();
471 dev->set_ifname(config->tap_ifname());
472 dev->set_ipv4_addr(config->guest_ipv4_addr());
473 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900474
Garrick Evans08843932019-09-17 14:41:08 +0900475 writer.AppendProtoAsArrayOfBytes(response);
476 return dbus_response;
477}
478
479std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
480 dbus::MethodCall* method_call) {
481 LOG(INFO) << "ARCVM shutting down";
482
483 std::unique_ptr<dbus::Response> dbus_response(
484 dbus::Response::FromMethodCall(method_call));
485
486 dbus::MessageReader reader(method_call);
487 dbus::MessageWriter writer(dbus_response.get());
488
489 patchpanel::ArcVmShutdownRequest request;
490 patchpanel::ArcVmShutdownResponse response;
491
492 if (!reader.PopArrayOfBytesAsProto(&request)) {
493 LOG(ERROR) << "Unable to parse request";
494 writer.AppendProtoAsArrayOfBytes(response);
495 return dbus_response;
496 }
497
Garrick Evans21173b12019-11-20 15:23:16 +0900498 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900499
Garrick Evans08843932019-09-17 14:41:08 +0900500 writer.AppendProtoAsArrayOfBytes(response);
501 return dbus_response;
502}
503
Garrick Evans47c19272019-11-21 10:58:21 +0900504std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
505 dbus::MethodCall* method_call) {
506 LOG(INFO) << "Termina VM starting up";
507
508 std::unique_ptr<dbus::Response> dbus_response(
509 dbus::Response::FromMethodCall(method_call));
510
511 dbus::MessageReader reader(method_call);
512 dbus::MessageWriter writer(dbus_response.get());
513
514 patchpanel::TerminaVmStartupRequest request;
515 patchpanel::TerminaVmStartupResponse response;
516
517 if (!reader.PopArrayOfBytesAsProto(&request)) {
518 LOG(ERROR) << "Unable to parse request";
519 writer.AppendProtoAsArrayOfBytes(response);
520 return dbus_response;
521 }
522
523 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900524 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900525 LOG(ERROR) << "Failed to start Termina VM network service";
526 writer.AppendProtoAsArrayOfBytes(response);
527 return dbus_response;
528 }
529
Garrick Evans51d5b552020-01-30 10:42:06 +0900530 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900531 if (!tap) {
532 LOG(DFATAL) << "TAP device missing";
533 writer.AppendProtoAsArrayOfBytes(response);
534 return dbus_response;
535 }
Garrick Evans47c19272019-11-21 10:58:21 +0900536
Garrick Evansb1c93712020-01-22 09:28:25 +0900537 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900538 dev->set_ifname(tap->host_ifname());
539 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900540 if (!subnet) {
541 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
542 writer.AppendProtoAsArrayOfBytes(response);
543 return dbus_response;
544 }
545 auto* resp_subnet = dev->mutable_ipv4_subnet();
546 resp_subnet->set_base_addr(subnet->BaseAddress());
547 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900548 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900549 if (!subnet) {
550 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
551 writer.AppendProtoAsArrayOfBytes(response);
552 return dbus_response;
553 }
554 resp_subnet = response.mutable_container_subnet();
555 resp_subnet->set_base_addr(subnet->BaseAddress());
556 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900557
558 writer.AppendProtoAsArrayOfBytes(response);
559 return dbus_response;
560}
561
562std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
563 dbus::MethodCall* method_call) {
564 LOG(INFO) << "Termina VM shutting down";
565
566 std::unique_ptr<dbus::Response> dbus_response(
567 dbus::Response::FromMethodCall(method_call));
568
569 dbus::MessageReader reader(method_call);
570 dbus::MessageWriter writer(dbus_response.get());
571
572 patchpanel::TerminaVmShutdownRequest request;
573 patchpanel::TerminaVmShutdownResponse response;
574
575 if (!reader.PopArrayOfBytesAsProto(&request)) {
576 LOG(ERROR) << "Unable to parse request";
577 writer.AppendProtoAsArrayOfBytes(response);
578 return dbus_response;
579 }
580
Garrick Evans51d5b552020-01-30 10:42:06 +0900581 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
582
583 writer.AppendProtoAsArrayOfBytes(response);
584 return dbus_response;
585}
586
587std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
588 dbus::MethodCall* method_call) {
589 LOG(INFO) << "Plugin VM starting up";
590
591 std::unique_ptr<dbus::Response> dbus_response(
592 dbus::Response::FromMethodCall(method_call));
593
594 dbus::MessageReader reader(method_call);
595 dbus::MessageWriter writer(dbus_response.get());
596
597 patchpanel::PluginVmStartupRequest request;
598 patchpanel::PluginVmStartupResponse response;
599
600 if (!reader.PopArrayOfBytesAsProto(&request)) {
601 LOG(ERROR) << "Unable to parse request";
602 writer.AppendProtoAsArrayOfBytes(response);
603 return dbus_response;
604 }
605
Garrick Evans08fb34b2020-02-20 10:50:17 +0900606 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900607 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900608 LOG(ERROR) << "Failed to start Plugin VM network service";
609 writer.AppendProtoAsArrayOfBytes(response);
610 return dbus_response;
611 }
612
613 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
614 if (!tap) {
615 LOG(DFATAL) << "TAP device missing";
616 writer.AppendProtoAsArrayOfBytes(response);
617 return dbus_response;
618 }
619
Garrick Evans51d5b552020-01-30 10:42:06 +0900620 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900621 dev->set_ifname(tap->host_ifname());
622 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900623 if (!subnet) {
624 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
625 writer.AppendProtoAsArrayOfBytes(response);
626 return dbus_response;
627 }
628 auto* resp_subnet = dev->mutable_ipv4_subnet();
629 resp_subnet->set_base_addr(subnet->BaseAddress());
630 resp_subnet->set_prefix_len(subnet->PrefixLength());
631
632 writer.AppendProtoAsArrayOfBytes(response);
633 return dbus_response;
634}
635
636std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
637 dbus::MethodCall* method_call) {
638 LOG(INFO) << "Plugin VM shutting down";
639
640 std::unique_ptr<dbus::Response> dbus_response(
641 dbus::Response::FromMethodCall(method_call));
642
643 dbus::MessageReader reader(method_call);
644 dbus::MessageWriter writer(dbus_response.get());
645
646 patchpanel::PluginVmShutdownRequest request;
647 patchpanel::PluginVmShutdownResponse response;
648
649 if (!reader.PopArrayOfBytesAsProto(&request)) {
650 LOG(ERROR) << "Unable to parse request";
651 writer.AppendProtoAsArrayOfBytes(response);
652 return dbus_response;
653 }
654
655 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900656
657 writer.AppendProtoAsArrayOfBytes(response);
658 return dbus_response;
659}
660
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900661std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
662 dbus::MethodCall* method_call) {
663 std::unique_ptr<dbus::Response> dbus_response(
664 dbus::Response::FromMethodCall(method_call));
665
666 dbus::MessageReader reader(method_call);
667 dbus::MessageWriter writer(dbus_response.get());
668
669 patchpanel::SetVpnIntentRequest request;
670 patchpanel::SetVpnIntentResponse response;
671
672 bool success = reader.PopArrayOfBytesAsProto(&request);
673 if (!success) {
674 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
675 // Do not return yet to make sure we close the received fd.
676 }
677
678 base::ScopedFD client_socket;
679 reader.PopFileDescriptor(&client_socket);
680
681 if (success)
682 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
683
684 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900685
686 writer.AppendProtoAsArrayOfBytes(response);
687 return dbus_response;
688}
689
690std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
691 dbus::MethodCall* method_call) {
692 std::unique_ptr<dbus::Response> dbus_response(
693 dbus::Response::FromMethodCall(method_call));
694
695 dbus::MessageReader reader(method_call);
696 dbus::MessageWriter writer(dbus_response.get());
697
698 patchpanel::ConnectNamespaceRequest request;
699 patchpanel::ConnectNamespaceResponse response;
700
Hugo Benichicc6850f2020-01-17 13:26:06 +0900701 bool success = true;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900702 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900703 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
704 // Do not return yet to make sure we close the received fd and
705 // validate other arguments.
706 success = false;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900707 }
708
Hugo Benichicc6850f2020-01-17 13:26:06 +0900709 base::ScopedFD client_fd;
710 reader.PopFileDescriptor(&client_fd);
711 if (!client_fd.is_valid()) {
712 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
713 success = false;
714 }
715
716 pid_t pid = request.pid();
717 {
718 ScopedNS ns(pid);
719 if (!ns.IsValid()) {
720 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
721 success = false;
722 }
723 }
724
725 const std::string& outbound_ifname = request.outbound_physical_device();
726 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
727 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
728 << outbound_ifname;
729 success = false;
730 }
731
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900732 if (success)
733 ConnectNamespace(std::move(client_fd), request, response);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900734
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900735 writer.AppendProtoAsArrayOfBytes(response);
736 return dbus_response;
737}
738
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900739void Manager::ConnectNamespace(
740 base::ScopedFD client_fd,
741 const patchpanel::ConnectNamespaceRequest& request,
742 patchpanel::ConnectNamespaceResponse& response) {
743 std::unique_ptr<Subnet> subnet =
744 addr_mgr_.AllocateIPv4Subnet(AddressManager::Guest::MINIJAIL_NETNS);
745 if (!subnet) {
746 LOG(ERROR) << "ConnectNamespaceRequest: exhausted IPv4 subnet space";
747 return;
748 }
749
750 const std::string ifname_id = std::to_string(connected_namespaces_next_id_);
751 const std::string host_ifname = "arc_ns" + ifname_id;
752 const std::string client_ifname = "veth" + ifname_id;
Hugo Benichie8758b52020-04-03 14:49:01 +0900753 const uint32_t host_ipv4_addr = subnet->AddressAtOffset(0);
754 const uint32_t client_ipv4_addr = subnet->AddressAtOffset(1);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900755
Hugo Benichie8758b52020-04-03 14:49:01 +0900756 // Veth interface configuration and client routing configuration:
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900757 // - create veth pair inside client namespace.
758 // - configure IPv4 address on remote veth inside client namespace.
Hugo Benichie8758b52020-04-03 14:49:01 +0900759 // - configure IPv4 address on local veth inside host namespace.
760 // - add a default IPv4 /0 route sending traffic to that remote veth.
761 // - bring back one veth to the host namespace, and set it up.
762 pid_t pid = request.pid();
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900763 if (!datapath_->ConnectVethPair(pid, host_ifname, client_ifname,
764 addr_mgr_.GenerateMacAddress(),
765 client_ipv4_addr, subnet->PrefixLength(),
766 false /* enable_multicast */)) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900767 LOG(ERROR) << "ConnectNamespaceRequest: failed to create veth pair for "
768 "namespace pid "
769 << pid;
770 return;
771 }
772 if (!datapath_->ConfigureInterface(
773 host_ifname, addr_mgr_.GenerateMacAddress(), host_ipv4_addr,
774 subnet->PrefixLength(), true /* link up */,
775 false /* enable_multicast */)) {
776 LOG(ERROR) << "ConnectNamespaceRequest: cannot configure host interface "
777 << host_ifname;
778 datapath_->RemoveInterface(host_ifname);
779 return;
780 }
781 {
782 ScopedNS ns(pid);
783 if (!ns.IsValid()) {
784 LOG(ERROR) << "ConnectNamespaceRequest: cannot enter client pid " << pid;
785 datapath_->RemoveInterface(host_ifname);
786 return;
787 }
788 if (!datapath_->AddIPv4Route(host_ipv4_addr, INADDR_ANY, INADDR_ANY)) {
789 LOG(ERROR)
790 << "ConnectNamespaceRequest: failed to add default /0 route to "
791 << host_ifname << " inside namespace pid " << pid;
792 datapath_->RemoveInterface(host_ifname);
793 return;
794 }
795 }
796
797 // Host namespace routing configuration
798 // - ingress: add route to client subnet via |host_ifname|.
799 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
800 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
801 // Note that by default unsolicited ingress traffic is not forwarded to the
802 // client namespace unless the client specifically set port forwarding
803 // through permission_broker DBus APIs.
804 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
805 // both ways between client namespace and other guest containers and VMs.
806 // TODO(hugobenichi) If outbound_physical_device is defined, then set strong
807 // routing to that interface routing table.
808 if (!datapath_->AddIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
809 subnet->Netmask())) {
810 LOG(ERROR)
811 << "ConnectNamespaceRequest: failed to set route to client namespace";
812 datapath_->RemoveInterface(host_ifname);
813 return;
814 }
815 if (!datapath_->AddOutboundIPv4(host_ifname)) {
816 LOG(ERROR) << "ConnectNamespaceRequest: failed to allow FORWARD for "
817 "traffic outgoing from "
818 << host_ifname;
819 datapath_->RemoveInterface(host_ifname);
820 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
821 subnet->Netmask());
822 return;
823 }
824 if (!datapath_->AddOutboundIPv4SNATMark(host_ifname)) {
825 LOG(ERROR) << "ConnectNamespaceRequest: failed to set SNAT for traffic "
826 "outgoing from "
827 << host_ifname;
828 datapath_->RemoveInterface(host_ifname);
829 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
830 subnet->Netmask());
831 datapath_->RemoveOutboundIPv4(host_ifname);
832 return;
833 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900834
Hugo Benichi7352ad92020-04-07 16:11:59 +0900835 // Dup the client fd into our own: this guarantees that the fd number will
836 // be stable and tied to the actual kernel resources used by the client.
837 base::ScopedFD local_client_fd(dup(client_fd.get()));
838 if (!local_client_fd.is_valid()) {
839 PLOG(ERROR) << "ConnectNamespaceRequest: failed to dup() client fd";
Hugo Benichie8758b52020-04-03 14:49:01 +0900840 datapath_->RemoveInterface(host_ifname);
841 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
842 subnet->Netmask());
843 datapath_->RemoveOutboundIPv4(host_ifname);
844 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900845 return;
846 }
847
848 // Add the dupe fd to the epoll watcher.
849 // TODO(hugobenichi) Find a way to reuse base::FileDescriptorWatcher for
850 // listening to EPOLLHUP.
851 struct epoll_event epevent;
852 epevent.events = EPOLLIN; // EPOLLERR | EPOLLHUP are always waited for.
853 epevent.data.fd = local_client_fd.get();
854 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_ADD,
855 local_client_fd.get(), &epevent) != 0) {
856 PLOG(ERROR) << "ConnectNamespaceResponse: epoll_ctl(EPOLL_CTL_ADD) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900857 datapath_->RemoveInterface(host_ifname);
858 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
859 subnet->Netmask());
860 datapath_->RemoveOutboundIPv4(host_ifname);
861 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900862 return;
863 }
864
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900865 // Prepare the response before storing ConnectNamespaceInfo.
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900866 response.set_peer_ifname(client_ifname);
867 response.set_peer_ipv4_address(host_ipv4_addr);
868 response.set_host_ifname(host_ifname);
869 response.set_host_ipv4_address(client_ipv4_addr);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900870 auto* response_subnet = response.mutable_ipv4_subnet();
871 response_subnet->set_base_addr(subnet->BaseAddress());
872 response_subnet->set_prefix_len(subnet->PrefixLength());
873
874 // Store ConnectNamespaceInfo
875 connected_namespaces_next_id_++;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900876 int fdkey = local_client_fd.release();
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900877 connected_namespaces_[fdkey] = {};
878 ConnectNamespaceInfo& ns_info = connected_namespaces_[fdkey];
879 ns_info.pid = request.pid();
880 ns_info.outbound_ifname = request.outbound_physical_device();
881 ns_info.host_ifname = std::move(host_ifname);
882 ns_info.client_ifname = std::move(client_ifname);
883 ns_info.client_subnet = std::move(subnet);
884
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900885 LOG(INFO) << "Connected network namespace " << ns_info;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900886
887 if (connected_namespaces_.size() == 1) {
888 LOG(INFO) << "Starting ConnectNamespace client fds monitoring";
889 CheckConnectedNamespaces();
890 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900891}
892
893void Manager::DisconnectNamespace(int client_fd) {
894 auto it = connected_namespaces_.find(client_fd);
895 if (it == connected_namespaces_.end()) {
896 LOG(ERROR) << "No ConnectNamespaceInfo found for client_fd " << client_fd;
897 return;
898 }
899
Hugo Benichi7352ad92020-04-07 16:11:59 +0900900 // Remove the client fd dupe from the epoll watcher and close it.
901 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL, client_fd,
Hugo Benichie8758b52020-04-03 14:49:01 +0900902 nullptr) != 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900903 PLOG(ERROR) << "DisconnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900904 if (close(client_fd) < 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900905 PLOG(ERROR) << "DisconnectNamespace: close(client_fd) failed";
Hugo Benichi7352ad92020-04-07 16:11:59 +0900906
Hugo Benichie8758b52020-04-03 14:49:01 +0900907 // Destroy the interface configuration and routing configuration:
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900908 // - destroy veth pair.
Hugo Benichie8758b52020-04-03 14:49:01 +0900909 // - remove forwarding rules on host namespace.
910 // - remove SNAT marking rule on host namespace.
911 // Note that the default route set inside the client namespace by patchpanel
912 // is not destroyed: it is assumed the client will also teardown its
913 // namespace if it triggered DisconnectNamespace.
914 datapath_->RemoveInterface(it->second.host_ifname);
915 datapath_->RemoveOutboundIPv4(it->second.host_ifname);
916 datapath_->RemoveOutboundIPv4SNATMark(it->second.host_ifname);
917 datapath_->DeleteIPv4Route(it->second.client_subnet->AddressAtOffset(0),
918 it->second.client_subnet->BaseAddress(),
919 it->second.client_subnet->Netmask());
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900920
921 LOG(INFO) << "Disconnected network namespace " << it->second;
922
923 // This release the allocated IPv4 subnet.
924 connected_namespaces_.erase(it);
925}
926
Hugo Benichi7352ad92020-04-07 16:11:59 +0900927// TODO(hugobenichi) Generalize this check to all resources created by
928// patchpanel on behalf of a remote client.
929void Manager::CheckConnectedNamespaces() {
930 int max_event = 10;
931 struct epoll_event epevents[max_event];
932 int nready = epoll_wait(connected_namespaces_epollfd_, epevents, max_event,
933 0 /* do not block */);
934 if (nready < 0)
935 PLOG(ERROR) << "CheckConnectedNamespaces: epoll_wait(0) failed";
936
937 for (int i = 0; i < nready; i++)
938 if (epevents[i].events & (EPOLLHUP | EPOLLERR))
939 DisconnectNamespace(epevents[i].data.fd);
940
941 if (connected_namespaces_.empty()) {
942 LOG(INFO) << "Stopping ConnectNamespace client fds monitoring";
943 return;
944 }
945
946 base::MessageLoopForIO::current()->task_runner()->PostDelayedTask(
947 FROM_HERE,
948 base::Bind(&Manager::CheckConnectedNamespaces,
Hugo Benichie8758b52020-04-03 14:49:01 +0900949 weak_factory_.GetWeakPtr()),
Hugo Benichi7352ad92020-04-07 16:11:59 +0900950 kConnectNamespaceCheckInterval);
951}
952
Garrick Evanse94a14e2019-11-11 10:32:13 +0900953void Manager::SendGuestMessage(const GuestMessage& msg) {
Garrick Evans96e03042019-05-28 14:30:52 +0900954 IpHelperMessage ipm;
955 *ipm.mutable_guest_message() = msg;
Garrick Evans96e03042019-05-28 14:30:52 +0900956 adb_proxy_->SendMessage(ipm);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900957 mcast_proxy_->SendMessage(ipm);
958 nd_proxy_->SendMessage(ipm);
Garrick Evans96e03042019-05-28 14:30:52 +0900959}
960
Garrick Evans4ac09852020-01-16 14:09:22 +0900961void Manager::StartForwarding(const std::string& ifname_physical,
962 const std::string& ifname_virtual,
Garrick Evans4ac09852020-01-16 14:09:22 +0900963 bool ipv6,
964 bool multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +0900965 if (ifname_physical.empty() || ifname_virtual.empty())
Garrick Evans4ac09852020-01-16 14:09:22 +0900966 return;
967
968 IpHelperMessage ipm;
969 DeviceMessage* msg = ipm.mutable_device_message();
970 msg->set_dev_ifname(ifname_physical);
Garrick Evans4ac09852020-01-16 14:09:22 +0900971 msg->set_br_ifname(ifname_virtual);
972
973 if (ipv6) {
974 LOG(INFO) << "Starting IPv6 forwarding from " << ifname_physical << " to "
975 << ifname_virtual;
976
977 if (!datapath_->AddIPv6Forwarding(ifname_physical, ifname_virtual)) {
978 LOG(ERROR) << "Failed to setup iptables forwarding rule for IPv6 from "
979 << ifname_physical << " to " << ifname_virtual;
980 }
981 if (!datapath_->MaskInterfaceFlags(ifname_physical, IFF_ALLMULTI)) {
982 LOG(WARNING) << "Failed to setup all multicast mode for interface "
983 << ifname_physical;
984 }
985 if (!datapath_->MaskInterfaceFlags(ifname_virtual, IFF_ALLMULTI)) {
986 LOG(WARNING) << "Failed to setup all multicast mode for interface "
987 << ifname_virtual;
988 }
989 nd_proxy_->SendMessage(ipm);
990 }
991
992 if (multicast) {
993 LOG(INFO) << "Starting multicast forwarding from " << ifname_physical
994 << " to " << ifname_virtual;
995 mcast_proxy_->SendMessage(ipm);
996 }
997}
998
999void Manager::StopForwarding(const std::string& ifname_physical,
1000 const std::string& ifname_virtual,
1001 bool ipv6,
1002 bool multicast) {
1003 if (ifname_physical.empty())
1004 return;
1005
1006 IpHelperMessage ipm;
1007 DeviceMessage* msg = ipm.mutable_device_message();
1008 msg->set_dev_ifname(ifname_physical);
1009 msg->set_teardown(true);
Taoyu Li7dca19a2020-03-16 16:27:07 +09001010 if (!ifname_virtual.empty()) {
1011 msg->set_br_ifname(ifname_virtual);
1012 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001013
1014 if (ipv6) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001015 if (ifname_virtual.empty()) {
1016 LOG(INFO) << "Stopping IPv6 forwarding on " << ifname_physical;
1017 } else {
1018 LOG(INFO) << "Stopping IPv6 forwarding from " << ifname_physical << " to "
1019 << ifname_virtual;
1020 datapath_->RemoveIPv6Forwarding(ifname_physical, ifname_virtual);
1021 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001022 nd_proxy_->SendMessage(ipm);
1023 }
1024
1025 if (multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001026 if (ifname_virtual.empty()) {
1027 LOG(INFO) << "Stopping multicast forwarding on " << ifname_physical;
1028 } else {
1029 LOG(INFO) << "Stopping multicast forwarding from " << ifname_physical
1030 << " to " << ifname_virtual;
1031 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001032 mcast_proxy_->SendMessage(ipm);
1033 }
1034}
1035
Garrick Evans4ac09852020-01-16 14:09:22 +09001036void Manager::OnDeviceMessageFromNDProxy(const DeviceMessage& msg) {
1037 LOG_IF(DFATAL, msg.dev_ifname().empty())
1038 << "Received DeviceMessage w/ empty dev_ifname";
1039
1040 if (!datapath_->AddIPv6HostRoute(msg.dev_ifname(), msg.guest_ip6addr(),
1041 128)) {
1042 LOG(WARNING) << "Failed to setup the IPv6 route for interface "
1043 << msg.dev_ifname();
1044 }
1045}
1046
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001047std::ostream& operator<<(std::ostream& stream,
1048 const Manager::ConnectNamespaceInfo& ns_info) {
1049 stream << "{ pid: " << ns_info.pid;
1050 if (!ns_info.outbound_ifname.empty()) {
1051 stream << ", outbound_ifname: " << ns_info.outbound_ifname;
1052 }
1053 stream << ", host_ifname: " << ns_info.host_ifname
1054 << ", client_ifname: " << ns_info.client_ifname
1055 << ", subnet: " << ns_info.client_subnet->ToCidrString() << '}';
1056 return stream;
1057}
1058
Garrick Evans3388a032020-03-24 11:25:55 +09001059} // namespace patchpanel