blob: 2f14964c5ccab89683f7f82049b7f517aba3d027 [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 Benichicc6850f2020-01-17 13:26:06 +090018#include <base/bind.h>
Taoyu Lia0727dc2020-09-24 19:54:59 +090019#include <base/files/scoped_file.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
Hugo Benichi7352ad92020-04-07 16:11:59 +090039// Time interval between epoll checks on file descriptors committed by callers
40// of ConnectNamespace DBus API.
41constexpr const base::TimeDelta kConnectNamespaceCheckInterval =
Hugo Benichifa9462e2020-06-26 09:50:48 +090042 base::TimeDelta::FromSeconds(5);
Hugo Benichi7352ad92020-04-07 16:11:59 +090043
Garrick Evans08843932019-09-17 14:41:08 +090044// Passes |method_call| to |handler| and passes the response to
45// |response_sender|. If |handler| returns nullptr, an empty response is
46// created and sent.
47void HandleSynchronousDBusMethodCall(
48 base::Callback<std::unique_ptr<dbus::Response>(dbus::MethodCall*)> handler,
49 dbus::MethodCall* method_call,
50 dbus::ExportedObject::ResponseSender response_sender) {
51 std::unique_ptr<dbus::Response> response = handler.Run(method_call);
52 if (!response)
53 response = dbus::Response::FromMethodCall(method_call);
Qijiang Fan0c657d42020-08-24 19:07:50 +090054 std::move(response_sender).Run(std::move(response));
Garrick Evans08843932019-09-17 14:41:08 +090055}
56
57} // namespace
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070058
Taoyu Lice7caa62019-10-01 15:43:33 +090059Manager::Manager(std::unique_ptr<HelperProcess> adb_proxy,
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090060 std::unique_ptr<HelperProcess> mcast_proxy,
Garrick Evans1f5a3612019-11-08 12:59:03 +090061 std::unique_ptr<HelperProcess> nd_proxy)
Garrick Evans3915af32019-07-25 15:44:34 +090062 : adb_proxy_(std::move(adb_proxy)),
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090063 mcast_proxy_(std::move(mcast_proxy)),
Garrick Evans4ee5ce22020-03-18 07:05:17 +090064 nd_proxy_(std::move(nd_proxy)) {
Taoyu Li179dcc62019-10-17 11:21:08 +090065 runner_ = std::make_unique<MinijailedProcessRunner>();
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090066 datapath_ = std::make_unique<Datapath>(runner_.get(), &firewall_);
Hugo Benichi7352ad92020-04-07 16:11:59 +090067 connected_namespaces_epollfd_ = epoll_create(1 /* size */);
Taoyu Li179dcc62019-10-17 11:21:08 +090068}
Long Chengd4415582019-09-24 19:16:09 +000069
Garrick Evans207e7482019-12-16 11:54:36 +090070Manager::~Manager() {
71 OnShutdown(nullptr);
72}
73
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +090074std::map<const std::string, bool> Manager::cached_feature_enabled_ = {};
75
76bool Manager::ShouldEnableFeature(
77 int min_android_sdk_version,
78 int min_chrome_milestone,
79 const std::vector<std::string>& supported_boards,
80 const std::string& feature_name) {
81 static const char kLsbReleasePath[] = "/etc/lsb-release";
82
83 const auto& cached_result = cached_feature_enabled_.find(feature_name);
84 if (cached_result != cached_feature_enabled_.end())
85 return cached_result->second;
86
87 auto check = [min_android_sdk_version, min_chrome_milestone,
88 &supported_boards, &feature_name]() {
89 brillo::KeyValueStore store;
90 if (!store.Load(base::FilePath(kLsbReleasePath))) {
91 LOG(ERROR) << "Could not read lsb-release";
92 return false;
93 }
94
95 std::string value;
96 if (!store.GetString("CHROMEOS_ARC_ANDROID_SDK_VERSION", &value)) {
97 LOG(ERROR) << feature_name
98 << " disabled - cannot determine Android SDK version";
99 return false;
100 }
101 int ver = 0;
102 if (!base::StringToInt(value.c_str(), &ver)) {
103 LOG(ERROR) << feature_name << " disabled - invalid Android SDK version";
104 return false;
105 }
106 if (ver < min_android_sdk_version) {
107 LOG(INFO) << feature_name << " disabled for Android SDK " << value;
108 return false;
109 }
110
111 if (!store.GetString("CHROMEOS_RELEASE_CHROME_MILESTONE", &value)) {
112 LOG(ERROR) << feature_name
113 << " disabled - cannot determine ChromeOS milestone";
114 return false;
115 }
116 if (!base::StringToInt(value.c_str(), &ver)) {
117 LOG(ERROR) << feature_name << " disabled - invalid ChromeOS milestone";
118 return false;
119 }
120 if (ver < min_chrome_milestone) {
121 LOG(INFO) << feature_name << " disabled for ChromeOS milestone " << value;
122 return false;
123 }
124
125 if (!store.GetString("CHROMEOS_RELEASE_BOARD", &value)) {
126 LOG(ERROR) << feature_name << " disabled - cannot determine board";
127 return false;
128 }
129 if (!supported_boards.empty() &&
130 std::find(supported_boards.begin(), supported_boards.end(), value) ==
131 supported_boards.end()) {
132 LOG(INFO) << feature_name << " disabled for board " << value;
133 return false;
134 }
135 return true;
136 };
137
138 bool result = check();
139 cached_feature_enabled_.emplace(feature_name, result);
140 return result;
141}
142
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700143int Manager::OnInit() {
Garrick Evans54861622019-07-19 09:05:09 +0900144 prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800145
146 // Handle subprocess lifecycle.
147 process_reaper_.Register(this);
Hugo Benichi935eca92018-07-03 13:47:24 +0900148
149 CHECK(process_reaper_.WatchForChild(
Garrick Evans96e03042019-05-28 14:30:52 +0900150 FROM_HERE, adb_proxy_->pid(),
151 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
152 adb_proxy_->pid())))
153 << "Failed to watch adb-proxy child process";
Taoyu Liaf944c92019-10-01 12:22:31 +0900154 CHECK(process_reaper_.WatchForChild(
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900155 FROM_HERE, mcast_proxy_->pid(),
156 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
157 nd_proxy_->pid())))
158 << "Failed to watch multicast-proxy child process";
159 CHECK(process_reaper_.WatchForChild(
Taoyu Liaf944c92019-10-01 12:22:31 +0900160 FROM_HERE, nd_proxy_->pid(),
161 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
162 nd_proxy_->pid())))
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900163 << "Failed to watch nd-proxy child process";
Garrick Evans96e03042019-05-28 14:30:52 +0900164
Garrick Evans49879532018-12-03 13:15:36 +0900165 // Run after Daemon::OnInit().
hschamf9546312020-04-14 15:12:40 +0900166 base::ThreadTaskRunnerHandle::Get()->PostTask(
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700167 FROM_HERE,
168 base::Bind(&Manager::InitialSetup, weak_factory_.GetWeakPtr()));
169
170 return DBusDaemon::OnInit();
171}
172
173void Manager::InitialSetup() {
Garrick Evans08843932019-09-17 14:41:08 +0900174 LOG(INFO) << "Setting up DBus service interface";
175 dbus_svc_path_ = bus_->GetExportedObject(
176 dbus::ObjectPath(patchpanel::kPatchPanelServicePath));
177 if (!dbus_svc_path_) {
178 LOG(FATAL) << "Failed to export " << patchpanel::kPatchPanelServicePath
179 << " object";
180 }
181
Hugo Benichi76be34a2020-08-26 22:35:54 +0900182 shill_client_ = std::make_unique<ShillClient>(bus_);
183
Garrick Evans08843932019-09-17 14:41:08 +0900184 using ServiceMethod =
185 std::unique_ptr<dbus::Response> (Manager::*)(dbus::MethodCall*);
186 const std::map<const char*, ServiceMethod> kServiceMethods = {
187 {patchpanel::kArcStartupMethod, &Manager::OnArcStartup},
188 {patchpanel::kArcShutdownMethod, &Manager::OnArcShutdown},
189 {patchpanel::kArcVmStartupMethod, &Manager::OnArcVmStartup},
190 {patchpanel::kArcVmShutdownMethod, &Manager::OnArcVmShutdown},
Garrick Evans47c19272019-11-21 10:58:21 +0900191 {patchpanel::kTerminaVmStartupMethod, &Manager::OnTerminaVmStartup},
192 {patchpanel::kTerminaVmShutdownMethod, &Manager::OnTerminaVmShutdown},
Garrick Evans51d5b552020-01-30 10:42:06 +0900193 {patchpanel::kPluginVmStartupMethod, &Manager::OnPluginVmStartup},
194 {patchpanel::kPluginVmShutdownMethod, &Manager::OnPluginVmShutdown},
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900195 {patchpanel::kSetVpnIntentMethod, &Manager::OnSetVpnIntent},
Hugo Benichib56b77c2020-01-15 16:00:56 +0900196 {patchpanel::kConnectNamespaceMethod, &Manager::OnConnectNamespace},
Jie Jiang493cde42020-07-17 21:43:39 +0900197 {patchpanel::kGetTrafficCountersMethod, &Manager::OnGetTrafficCounters},
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900198 {patchpanel::kModifyPortRuleMethod, &Manager::OnModifyPortRule},
Garrick Evans08843932019-09-17 14:41:08 +0900199 };
200
201 for (const auto& kv : kServiceMethods) {
202 if (!dbus_svc_path_->ExportMethodAndBlock(
203 patchpanel::kPatchPanelInterface, kv.first,
204 base::Bind(&HandleSynchronousDBusMethodCall,
205 base::Bind(kv.second, base::Unretained(this))))) {
206 LOG(FATAL) << "Failed to export method " << kv.first;
207 }
208 }
209
210 if (!bus_->RequestOwnershipAndBlock(patchpanel::kPatchPanelServiceName,
211 dbus::Bus::REQUIRE_PRIMARY)) {
212 LOG(FATAL) << "Failed to take ownership of "
213 << patchpanel::kPatchPanelServiceName;
214 }
215 LOG(INFO) << "DBus service interface ready";
216
Hugo Benichifda77232020-08-21 18:28:15 +0900217 routing_svc_ = std::make_unique<RoutingService>();
218
Hugo Benichibf811c62020-09-07 17:30:45 +0900219 // b/162966185: Allow Jetstream to disable:
220 // - the IP forwarding setup used for hosting VMs and containers,
221 // - the iptables rules for fwmark based routing.
222 if (!USE_JETSTREAM_ROUTING) {
223 datapath_->Start();
224 shill_client_->RegisterDevicesChangedHandler(base::BindRepeating(
225 &Manager::OnDevicesChanged, weak_factory_.GetWeakPtr()));
226 }
Hugo Benichifda77232020-08-21 18:28:15 +0900227
Taoyu Lia0727dc2020-09-24 19:54:59 +0900228 nd_proxy_->RegisterNDProxyMessageHandler(
229 base::Bind(&Manager::OnNDProxyMessage, weak_factory_.GetWeakPtr()));
Hugo Benichifda77232020-08-21 18:28:15 +0900230
Hugo Benichifda77232020-08-21 18:28:15 +0900231 auto* const forwarder = static_cast<TrafficForwarder*>(this);
232
233 GuestMessage::GuestType arc_guest =
234 USE_ARCVM ? GuestMessage::ARC_VM : GuestMessage::ARC;
235 arc_svc_ = std::make_unique<ArcService>(shill_client_.get(), datapath_.get(),
236 &addr_mgr_, forwarder, arc_guest);
237 cros_svc_ = std::make_unique<CrostiniService>(shill_client_.get(), &addr_mgr_,
238 datapath_.get(), forwarder);
Jie Jiang84966852020-09-18 18:49:05 +0900239 network_monitor_svc_ = std::make_unique<NetworkMonitorService>(
240 shill_client_.get(),
241 base::BindRepeating(&Manager::OnNeighborConnectedStateChanged,
242 weak_factory_.GetWeakPtr()));
Hugo Benichifda77232020-08-21 18:28:15 +0900243 network_monitor_svc_->Start();
244
245 counters_svc_ =
246 std::make_unique<CountersService>(shill_client_.get(), runner_.get());
247
248 nd_proxy_->Listen();
249}
250
251void Manager::OnShutdown(int* exit_code) {
252 LOG(INFO) << "Shutting down and cleaning up";
Jie Jiang84966852020-09-18 18:49:05 +0900253 network_monitor_svc_.reset();
Hugo Benichifda77232020-08-21 18:28:15 +0900254 cros_svc_.reset();
255 arc_svc_.reset();
256 close(connected_namespaces_epollfd_);
257 // Tear down any remaining connected namespace.
258 std::vector<int> connected_namespaces_fdkeys;
259 for (const auto& kv : connected_namespaces_)
260 connected_namespaces_fdkeys.push_back(kv.first);
261 for (const int fdkey : connected_namespaces_fdkeys)
262 DisconnectNamespace(fdkey);
Hugo Benichibf811c62020-09-07 17:30:45 +0900263 if (!USE_JETSTREAM_ROUTING)
264 datapath_->Stop();
Hugo Benichifda77232020-08-21 18:28:15 +0900265}
266
267void Manager::OnSubprocessExited(pid_t pid, const siginfo_t&) {
268 LOG(ERROR) << "Subprocess " << pid << " exited unexpectedly -"
269 << " attempting to restart";
270
271 HelperProcess* proc;
272 if (pid == adb_proxy_->pid()) {
273 proc = adb_proxy_.get();
274 } else if (pid == mcast_proxy_->pid()) {
275 proc = mcast_proxy_.get();
276 } else if (pid == nd_proxy_->pid()) {
277 proc = nd_proxy_.get();
278 } else {
279 LOG(DFATAL) << "Unknown child process";
280 return;
281 }
282
283 process_reaper_.ForgetChild(pid);
284
285 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
286 FROM_HERE,
287 base::Bind(&Manager::RestartSubprocess, weak_factory_.GetWeakPtr(), proc),
288 base::TimeDelta::FromMilliseconds((2 << proc->restarts()) *
289 kSubprocessRestartDelayMs));
290}
291
292void Manager::RestartSubprocess(HelperProcess* subproc) {
293 if (subproc->Restart()) {
294 DCHECK(process_reaper_.WatchForChild(
295 FROM_HERE, subproc->pid(),
296 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
297 subproc->pid())))
298 << "Failed to watch child process " << subproc->pid();
299 }
300}
301
Hugo Benichi76be34a2020-08-26 22:35:54 +0900302void Manager::OnDevicesChanged(const std::set<std::string>& added,
303 const std::set<std::string>& removed) {
304 for (const std::string& ifname : removed)
305 datapath_->StopConnectionPinning(ifname);
306
307 for (const std::string& ifname : added)
308 datapath_->StartConnectionPinning(ifname);
309}
310
Garrick Evanse94a14e2019-11-11 10:32:13 +0900311bool Manager::StartArc(pid_t pid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900312 if (!arc_svc_->Start(pid))
313 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900314
315 GuestMessage msg;
316 msg.set_event(GuestMessage::START);
317 msg.set_type(GuestMessage::ARC);
318 msg.set_arc_pid(pid);
319 SendGuestMessage(msg);
320
321 return true;
322}
323
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900324void Manager::StopArc() {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900325 GuestMessage msg;
326 msg.set_event(GuestMessage::STOP);
327 msg.set_type(GuestMessage::ARC);
328 SendGuestMessage(msg);
329
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900330 // After the ARC container has stopped, the pid is not known anymore.
331 // The pid argument is ignored by ArcService.
332 arc_svc_->Stop(0);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900333}
334
Garrick Evans015b0d62020-02-07 09:06:38 +0900335bool Manager::StartArcVm(uint32_t cid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900336 if (!arc_svc_->Start(cid))
337 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900338
339 GuestMessage msg;
340 msg.set_event(GuestMessage::START);
341 msg.set_type(GuestMessage::ARC_VM);
342 msg.set_arcvm_vsock_cid(cid);
343 SendGuestMessage(msg);
344
345 return true;
346}
347
Garrick Evans015b0d62020-02-07 09:06:38 +0900348void Manager::StopArcVm(uint32_t cid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900349 GuestMessage msg;
350 msg.set_event(GuestMessage::STOP);
351 msg.set_type(GuestMessage::ARC_VM);
352 SendGuestMessage(msg);
353
Garrick Evans21173b12019-11-20 15:23:16 +0900354 arc_svc_->Stop(cid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900355}
356
Garrick Evans51d5b552020-01-30 10:42:06 +0900357bool Manager::StartCrosVm(uint64_t vm_id,
358 GuestMessage::GuestType vm_type,
Garrick Evans53a2a982020-02-05 10:53:35 +0900359 uint32_t subnet_index) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900360 DCHECK(vm_type == GuestMessage::TERMINA_VM ||
361 vm_type == GuestMessage::PLUGIN_VM);
362
363 if (!cros_svc_->Start(vm_id, vm_type == GuestMessage::TERMINA_VM,
364 subnet_index))
Garrick Evans47c19272019-11-21 10:58:21 +0900365 return false;
366
367 GuestMessage msg;
368 msg.set_event(GuestMessage::START);
Garrick Evans51d5b552020-01-30 10:42:06 +0900369 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900370 SendGuestMessage(msg);
371
372 return true;
373}
374
Garrick Evans51d5b552020-01-30 10:42:06 +0900375void Manager::StopCrosVm(uint64_t vm_id, GuestMessage::GuestType vm_type) {
Garrick Evans47c19272019-11-21 10:58:21 +0900376 GuestMessage msg;
377 msg.set_event(GuestMessage::STOP);
Garrick Evans51d5b552020-01-30 10:42:06 +0900378 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900379 SendGuestMessage(msg);
380
Garrick Evans51d5b552020-01-30 10:42:06 +0900381 cros_svc_->Stop(vm_id, vm_type == GuestMessage::TERMINA_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900382}
383
Garrick Evans08843932019-09-17 14:41:08 +0900384std::unique_ptr<dbus::Response> Manager::OnArcStartup(
385 dbus::MethodCall* method_call) {
386 LOG(INFO) << "ARC++ starting up";
387
388 std::unique_ptr<dbus::Response> dbus_response(
389 dbus::Response::FromMethodCall(method_call));
390
391 dbus::MessageReader reader(method_call);
392 dbus::MessageWriter writer(dbus_response.get());
393
394 patchpanel::ArcStartupRequest request;
395 patchpanel::ArcStartupResponse response;
396
397 if (!reader.PopArrayOfBytesAsProto(&request)) {
398 LOG(ERROR) << "Unable to parse request";
399 writer.AppendProtoAsArrayOfBytes(response);
400 return dbus_response;
401 }
402
Garrick Evanse01bf072019-11-15 09:08:19 +0900403 if (!StartArc(request.pid()))
404 LOG(ERROR) << "Failed to start ARC++ network service";
Garrick Evanse94a14e2019-11-11 10:32:13 +0900405
Garrick Evans08843932019-09-17 14:41:08 +0900406 writer.AppendProtoAsArrayOfBytes(response);
407 return dbus_response;
408}
409
410std::unique_ptr<dbus::Response> Manager::OnArcShutdown(
411 dbus::MethodCall* method_call) {
412 LOG(INFO) << "ARC++ shutting down";
413
414 std::unique_ptr<dbus::Response> dbus_response(
415 dbus::Response::FromMethodCall(method_call));
416
417 dbus::MessageReader reader(method_call);
418 dbus::MessageWriter writer(dbus_response.get());
419
420 patchpanel::ArcShutdownRequest request;
421 patchpanel::ArcShutdownResponse response;
422
423 if (!reader.PopArrayOfBytesAsProto(&request)) {
424 LOG(ERROR) << "Unable to parse request";
425 writer.AppendProtoAsArrayOfBytes(response);
426 return dbus_response;
427 }
428
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900429 StopArc();
Garrick Evanse94a14e2019-11-11 10:32:13 +0900430
Garrick Evans08843932019-09-17 14:41:08 +0900431 writer.AppendProtoAsArrayOfBytes(response);
432 return dbus_response;
433}
434
435std::unique_ptr<dbus::Response> Manager::OnArcVmStartup(
436 dbus::MethodCall* method_call) {
437 LOG(INFO) << "ARCVM starting up";
438
439 std::unique_ptr<dbus::Response> dbus_response(
440 dbus::Response::FromMethodCall(method_call));
441
442 dbus::MessageReader reader(method_call);
443 dbus::MessageWriter writer(dbus_response.get());
444
445 patchpanel::ArcVmStartupRequest request;
446 patchpanel::ArcVmStartupResponse response;
447
448 if (!reader.PopArrayOfBytesAsProto(&request)) {
449 LOG(ERROR) << "Unable to parse request";
450 writer.AppendProtoAsArrayOfBytes(response);
451 return dbus_response;
452 }
453
Garrick Evans47c19272019-11-21 10:58:21 +0900454 if (!StartArcVm(request.cid())) {
Garrick Evanse01bf072019-11-15 09:08:19 +0900455 LOG(ERROR) << "Failed to start ARCVM network service";
Garrick Evans47c19272019-11-21 10:58:21 +0900456 writer.AppendProtoAsArrayOfBytes(response);
457 return dbus_response;
Garrick Evanse01bf072019-11-15 09:08:19 +0900458 }
Garrick Evanse94a14e2019-11-11 10:32:13 +0900459
Garrick Evans47c19272019-11-21 10:58:21 +0900460 // Populate the response with the known devices.
Garrick Evans38b25a42020-04-06 15:17:42 +0900461 for (const auto* config : arc_svc_->GetDeviceConfigs()) {
462 if (config->tap_ifname().empty())
463 continue;
Garrick Evans47c19272019-11-21 10:58:21 +0900464
Garrick Evans38b25a42020-04-06 15:17:42 +0900465 auto* dev = response.add_devices();
466 dev->set_ifname(config->tap_ifname());
467 dev->set_ipv4_addr(config->guest_ipv4_addr());
468 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900469
Garrick Evans08843932019-09-17 14:41:08 +0900470 writer.AppendProtoAsArrayOfBytes(response);
471 return dbus_response;
472}
473
474std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
475 dbus::MethodCall* method_call) {
476 LOG(INFO) << "ARCVM shutting down";
477
478 std::unique_ptr<dbus::Response> dbus_response(
479 dbus::Response::FromMethodCall(method_call));
480
481 dbus::MessageReader reader(method_call);
482 dbus::MessageWriter writer(dbus_response.get());
483
484 patchpanel::ArcVmShutdownRequest request;
485 patchpanel::ArcVmShutdownResponse response;
486
487 if (!reader.PopArrayOfBytesAsProto(&request)) {
488 LOG(ERROR) << "Unable to parse request";
489 writer.AppendProtoAsArrayOfBytes(response);
490 return dbus_response;
491 }
492
Garrick Evans21173b12019-11-20 15:23:16 +0900493 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900494
Garrick Evans08843932019-09-17 14:41:08 +0900495 writer.AppendProtoAsArrayOfBytes(response);
496 return dbus_response;
497}
498
Garrick Evans47c19272019-11-21 10:58:21 +0900499std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
500 dbus::MethodCall* method_call) {
501 LOG(INFO) << "Termina VM starting up";
502
503 std::unique_ptr<dbus::Response> dbus_response(
504 dbus::Response::FromMethodCall(method_call));
505
506 dbus::MessageReader reader(method_call);
507 dbus::MessageWriter writer(dbus_response.get());
508
509 patchpanel::TerminaVmStartupRequest request;
510 patchpanel::TerminaVmStartupResponse response;
511
512 if (!reader.PopArrayOfBytesAsProto(&request)) {
513 LOG(ERROR) << "Unable to parse request";
514 writer.AppendProtoAsArrayOfBytes(response);
515 return dbus_response;
516 }
517
518 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900519 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900520 LOG(ERROR) << "Failed to start Termina VM network service";
521 writer.AppendProtoAsArrayOfBytes(response);
522 return dbus_response;
523 }
524
Garrick Evans51d5b552020-01-30 10:42:06 +0900525 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900526 if (!tap) {
527 LOG(DFATAL) << "TAP device missing";
528 writer.AppendProtoAsArrayOfBytes(response);
529 return dbus_response;
530 }
Garrick Evans47c19272019-11-21 10:58:21 +0900531
Garrick Evansb1c93712020-01-22 09:28:25 +0900532 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900533 dev->set_ifname(tap->host_ifname());
534 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900535 if (!subnet) {
536 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
537 writer.AppendProtoAsArrayOfBytes(response);
538 return dbus_response;
539 }
540 auto* resp_subnet = dev->mutable_ipv4_subnet();
541 resp_subnet->set_base_addr(subnet->BaseAddress());
542 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900543 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900544 if (!subnet) {
545 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
546 writer.AppendProtoAsArrayOfBytes(response);
547 return dbus_response;
548 }
549 resp_subnet = response.mutable_container_subnet();
550 resp_subnet->set_base_addr(subnet->BaseAddress());
551 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900552
553 writer.AppendProtoAsArrayOfBytes(response);
554 return dbus_response;
555}
556
557std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
558 dbus::MethodCall* method_call) {
559 LOG(INFO) << "Termina VM shutting down";
560
561 std::unique_ptr<dbus::Response> dbus_response(
562 dbus::Response::FromMethodCall(method_call));
563
564 dbus::MessageReader reader(method_call);
565 dbus::MessageWriter writer(dbus_response.get());
566
567 patchpanel::TerminaVmShutdownRequest request;
568 patchpanel::TerminaVmShutdownResponse response;
569
570 if (!reader.PopArrayOfBytesAsProto(&request)) {
571 LOG(ERROR) << "Unable to parse request";
572 writer.AppendProtoAsArrayOfBytes(response);
573 return dbus_response;
574 }
575
Garrick Evans51d5b552020-01-30 10:42:06 +0900576 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
577
578 writer.AppendProtoAsArrayOfBytes(response);
579 return dbus_response;
580}
581
582std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
583 dbus::MethodCall* method_call) {
584 LOG(INFO) << "Plugin VM starting up";
585
586 std::unique_ptr<dbus::Response> dbus_response(
587 dbus::Response::FromMethodCall(method_call));
588
589 dbus::MessageReader reader(method_call);
590 dbus::MessageWriter writer(dbus_response.get());
591
592 patchpanel::PluginVmStartupRequest request;
593 patchpanel::PluginVmStartupResponse response;
594
595 if (!reader.PopArrayOfBytesAsProto(&request)) {
596 LOG(ERROR) << "Unable to parse request";
597 writer.AppendProtoAsArrayOfBytes(response);
598 return dbus_response;
599 }
600
Garrick Evans08fb34b2020-02-20 10:50:17 +0900601 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900602 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900603 LOG(ERROR) << "Failed to start Plugin VM network service";
604 writer.AppendProtoAsArrayOfBytes(response);
605 return dbus_response;
606 }
607
608 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
609 if (!tap) {
610 LOG(DFATAL) << "TAP device missing";
611 writer.AppendProtoAsArrayOfBytes(response);
612 return dbus_response;
613 }
614
Garrick Evans51d5b552020-01-30 10:42:06 +0900615 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900616 dev->set_ifname(tap->host_ifname());
617 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900618 if (!subnet) {
619 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
620 writer.AppendProtoAsArrayOfBytes(response);
621 return dbus_response;
622 }
623 auto* resp_subnet = dev->mutable_ipv4_subnet();
624 resp_subnet->set_base_addr(subnet->BaseAddress());
625 resp_subnet->set_prefix_len(subnet->PrefixLength());
626
627 writer.AppendProtoAsArrayOfBytes(response);
628 return dbus_response;
629}
630
631std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
632 dbus::MethodCall* method_call) {
633 LOG(INFO) << "Plugin VM shutting down";
634
635 std::unique_ptr<dbus::Response> dbus_response(
636 dbus::Response::FromMethodCall(method_call));
637
638 dbus::MessageReader reader(method_call);
639 dbus::MessageWriter writer(dbus_response.get());
640
641 patchpanel::PluginVmShutdownRequest request;
642 patchpanel::PluginVmShutdownResponse response;
643
644 if (!reader.PopArrayOfBytesAsProto(&request)) {
645 LOG(ERROR) << "Unable to parse request";
646 writer.AppendProtoAsArrayOfBytes(response);
647 return dbus_response;
648 }
649
650 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900651
652 writer.AppendProtoAsArrayOfBytes(response);
653 return dbus_response;
654}
655
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900656std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
657 dbus::MethodCall* method_call) {
658 std::unique_ptr<dbus::Response> dbus_response(
659 dbus::Response::FromMethodCall(method_call));
660
661 dbus::MessageReader reader(method_call);
662 dbus::MessageWriter writer(dbus_response.get());
663
664 patchpanel::SetVpnIntentRequest request;
665 patchpanel::SetVpnIntentResponse response;
666
667 bool success = reader.PopArrayOfBytesAsProto(&request);
668 if (!success) {
669 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
670 // Do not return yet to make sure we close the received fd.
671 }
672
673 base::ScopedFD client_socket;
674 reader.PopFileDescriptor(&client_socket);
675
676 if (success)
677 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
678
679 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900680
681 writer.AppendProtoAsArrayOfBytes(response);
682 return dbus_response;
683}
684
685std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
686 dbus::MethodCall* method_call) {
687 std::unique_ptr<dbus::Response> dbus_response(
688 dbus::Response::FromMethodCall(method_call));
689
690 dbus::MessageReader reader(method_call);
691 dbus::MessageWriter writer(dbus_response.get());
692
693 patchpanel::ConnectNamespaceRequest request;
694 patchpanel::ConnectNamespaceResponse response;
695
Hugo Benichicc6850f2020-01-17 13:26:06 +0900696 bool success = true;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900697 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900698 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
699 // Do not return yet to make sure we close the received fd and
700 // validate other arguments.
701 success = false;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900702 }
703
Hugo Benichicc6850f2020-01-17 13:26:06 +0900704 base::ScopedFD client_fd;
705 reader.PopFileDescriptor(&client_fd);
706 if (!client_fd.is_valid()) {
707 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
708 success = false;
709 }
710
711 pid_t pid = request.pid();
712 {
713 ScopedNS ns(pid);
714 if (!ns.IsValid()) {
715 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
716 success = false;
717 }
718 }
719
720 const std::string& outbound_ifname = request.outbound_physical_device();
721 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
722 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
723 << outbound_ifname;
724 success = false;
725 }
726
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900727 if (success)
728 ConnectNamespace(std::move(client_fd), request, response);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900729
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900730 writer.AppendProtoAsArrayOfBytes(response);
731 return dbus_response;
732}
733
Jie Jiang493cde42020-07-17 21:43:39 +0900734std::unique_ptr<dbus::Response> Manager::OnGetTrafficCounters(
735 dbus::MethodCall* method_call) {
736 std::unique_ptr<dbus::Response> dbus_response(
737 dbus::Response::FromMethodCall(method_call));
738
739 dbus::MessageReader reader(method_call);
740 dbus::MessageWriter writer(dbus_response.get());
741
742 patchpanel::TrafficCountersRequest request;
743 patchpanel::TrafficCountersResponse response;
744
745 if (!reader.PopArrayOfBytesAsProto(&request)) {
746 LOG(ERROR) << "Unable to parse TrafficCountersRequest";
747 writer.AppendProtoAsArrayOfBytes(response);
748 return dbus_response;
749 }
750
751 const std::set<std::string> devices{request.devices().begin(),
752 request.devices().end()};
753 const auto counters = counters_svc_->GetCounters(devices);
754 for (const auto& kv : counters) {
755 auto* traffic_counter = response.add_counters();
756 const auto& source_and_device = kv.first;
757 const auto& counter = kv.second;
758 traffic_counter->set_source(source_and_device.first);
759 traffic_counter->set_device(source_and_device.second);
760 traffic_counter->set_rx_bytes(counter.rx_bytes);
761 traffic_counter->set_rx_packets(counter.rx_packets);
762 traffic_counter->set_tx_bytes(counter.tx_bytes);
763 traffic_counter->set_tx_packets(counter.tx_packets);
764 }
765
766 writer.AppendProtoAsArrayOfBytes(response);
767 return dbus_response;
768}
769
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900770std::unique_ptr<dbus::Response> Manager::OnModifyPortRule(
771 dbus::MethodCall* method_call) {
772 std::unique_ptr<dbus::Response> dbus_response(
773 dbus::Response::FromMethodCall(method_call));
774
775 dbus::MessageReader reader(method_call);
776 dbus::MessageWriter writer(dbus_response.get());
777
778 patchpanel::ModifyPortRuleRequest request;
779 patchpanel::ModifyPortRuleResponse response;
780
781 if (!reader.PopArrayOfBytesAsProto(&request)) {
782 LOG(ERROR) << "Unable to parse ModifyPortRequest";
783 writer.AppendProtoAsArrayOfBytes(response);
784 return dbus_response;
785 }
786
Jason Jeremy Imanc28df852020-07-11 17:38:26 +0900787 response.set_success(ModifyPortRule(request));
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900788 writer.AppendProtoAsArrayOfBytes(response);
789 return dbus_response;
790}
791
Jie Jiang84966852020-09-18 18:49:05 +0900792void Manager::OnNeighborConnectedStateChanged(
793 int ifindex,
794 const shill::IPAddress& ip_addr,
795 NeighborLinkMonitor::NeighborRole role,
796 bool connected) {
797 if (!ip_addr.IsValid()) {
798 LOG(DFATAL) << "ip_addr is not valid";
799 return;
800 }
801
802 using SignalProto = NeighborConnectedStateChangedSignal;
803 SignalProto proto;
804 proto.set_ifindex(ifindex);
805 proto.set_ip_addr(ip_addr.ToString());
806 switch (role) {
807 case NeighborLinkMonitor::NeighborRole::kGateway:
808 proto.set_role(SignalProto::GATEWAY);
809 break;
810 case NeighborLinkMonitor::NeighborRole::kDNSServer:
811 proto.set_role(SignalProto::DNS_SERVER);
812 break;
813 case NeighborLinkMonitor::NeighborRole::kGatewayAndDNSServer:
814 proto.set_role(SignalProto::GATEWAY_AND_DNS_SERVER);
815 break;
816 default:
817 NOTREACHED();
818 }
819
820 dbus::Signal signal(kPatchPanelInterface,
821 kNeighborConnectedStateChangedSignal);
822 dbus::MessageWriter writer(&signal);
823 if (!writer.AppendProtoAsArrayOfBytes(proto)) {
824 LOG(ERROR) << "Failed to encode proto NeighborConnectedStateChangedSignal";
825 return;
826 }
827
828 dbus_svc_path_->SendSignal(&signal);
829}
830
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900831void Manager::ConnectNamespace(
832 base::ScopedFD client_fd,
833 const patchpanel::ConnectNamespaceRequest& request,
834 patchpanel::ConnectNamespaceResponse& response) {
835 std::unique_ptr<Subnet> subnet =
836 addr_mgr_.AllocateIPv4Subnet(AddressManager::Guest::MINIJAIL_NETNS);
837 if (!subnet) {
838 LOG(ERROR) << "ConnectNamespaceRequest: exhausted IPv4 subnet space";
839 return;
840 }
841
842 const std::string ifname_id = std::to_string(connected_namespaces_next_id_);
Hugo Benichi33860d72020-07-09 16:34:01 +0900843 const std::string netns_name = "connected_netns_" + ifname_id;
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900844 const std::string host_ifname = "arc_ns" + ifname_id;
845 const std::string client_ifname = "veth" + ifname_id;
Hugo Benichie8758b52020-04-03 14:49:01 +0900846 const uint32_t host_ipv4_addr = subnet->AddressAtOffset(0);
847 const uint32_t client_ipv4_addr = subnet->AddressAtOffset(1);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900848
Hugo Benichie8758b52020-04-03 14:49:01 +0900849 // Veth interface configuration and client routing configuration:
Hugo Benichi33860d72020-07-09 16:34:01 +0900850 // - attach a name to the client namespace.
851 // - create veth pair across the current namespace and the client namespace.
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900852 // - configure IPv4 address on remote veth inside client namespace.
Hugo Benichie8758b52020-04-03 14:49:01 +0900853 // - configure IPv4 address on local veth inside host namespace.
854 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichie8758b52020-04-03 14:49:01 +0900855 pid_t pid = request.pid();
Hugo Benichi33860d72020-07-09 16:34:01 +0900856 if (!datapath_->NetnsAttachName(netns_name, pid)) {
857 LOG(ERROR) << "ConnectNamespaceRequest: failed to attach name "
858 << netns_name << " to namespace pid " << pid;
859 return;
860 }
861 if (!datapath_->ConnectVethPair(pid, netns_name, host_ifname, client_ifname,
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900862 addr_mgr_.GenerateMacAddress(),
863 client_ipv4_addr, subnet->PrefixLength(),
864 false /* enable_multicast */)) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900865 LOG(ERROR) << "ConnectNamespaceRequest: failed to create veth pair for "
866 "namespace pid "
867 << pid;
Hugo Benichi33860d72020-07-09 16:34:01 +0900868 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900869 return;
870 }
871 if (!datapath_->ConfigureInterface(
872 host_ifname, addr_mgr_.GenerateMacAddress(), host_ipv4_addr,
873 subnet->PrefixLength(), true /* link up */,
874 false /* enable_multicast */)) {
875 LOG(ERROR) << "ConnectNamespaceRequest: cannot configure host interface "
876 << host_ifname;
877 datapath_->RemoveInterface(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900878 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900879 return;
880 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900881 bool peer_route_setup_success;
Hugo Benichie8758b52020-04-03 14:49:01 +0900882 {
883 ScopedNS ns(pid);
Hugo Benichi33860d72020-07-09 16:34:01 +0900884 peer_route_setup_success =
885 ns.IsValid() &&
886 datapath_->AddIPv4Route(host_ipv4_addr, INADDR_ANY, INADDR_ANY);
887 }
888 if (!peer_route_setup_success) {
889 LOG(ERROR) << "ConnectNamespaceRequest: failed to add default /0 route to "
890 << host_ifname << " inside namespace pid " << pid;
891 datapath_->RemoveInterface(host_ifname);
892 datapath_->NetnsDeleteName(netns_name);
893 return;
Hugo Benichie8758b52020-04-03 14:49:01 +0900894 }
895
896 // Host namespace routing configuration
897 // - ingress: add route to client subnet via |host_ifname|.
898 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
899 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
900 // Note that by default unsolicited ingress traffic is not forwarded to the
901 // client namespace unless the client specifically set port forwarding
902 // through permission_broker DBus APIs.
903 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
904 // both ways between client namespace and other guest containers and VMs.
905 // TODO(hugobenichi) If outbound_physical_device is defined, then set strong
906 // routing to that interface routing table.
907 if (!datapath_->AddIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
908 subnet->Netmask())) {
909 LOG(ERROR)
910 << "ConnectNamespaceRequest: failed to set route to client namespace";
911 datapath_->RemoveInterface(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900912 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900913 return;
914 }
915 if (!datapath_->AddOutboundIPv4(host_ifname)) {
916 LOG(ERROR) << "ConnectNamespaceRequest: failed to allow FORWARD for "
917 "traffic outgoing from "
918 << host_ifname;
919 datapath_->RemoveInterface(host_ifname);
920 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
921 subnet->Netmask());
Hugo Benichi33860d72020-07-09 16:34:01 +0900922 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900923 return;
924 }
925 if (!datapath_->AddOutboundIPv4SNATMark(host_ifname)) {
926 LOG(ERROR) << "ConnectNamespaceRequest: failed to set SNAT for traffic "
927 "outgoing from "
928 << host_ifname;
929 datapath_->RemoveInterface(host_ifname);
930 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
931 subnet->Netmask());
932 datapath_->RemoveOutboundIPv4(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900933 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900934 return;
935 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900936
Hugo Benichi7352ad92020-04-07 16:11:59 +0900937 // Dup the client fd into our own: this guarantees that the fd number will
938 // be stable and tied to the actual kernel resources used by the client.
939 base::ScopedFD local_client_fd(dup(client_fd.get()));
940 if (!local_client_fd.is_valid()) {
941 PLOG(ERROR) << "ConnectNamespaceRequest: failed to dup() client fd";
Hugo Benichie8758b52020-04-03 14:49:01 +0900942 datapath_->RemoveInterface(host_ifname);
943 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
944 subnet->Netmask());
945 datapath_->RemoveOutboundIPv4(host_ifname);
946 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900947 datapath_->NetnsDeleteName(netns_name);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900948 return;
949 }
950
951 // Add the dupe fd to the epoll watcher.
952 // TODO(hugobenichi) Find a way to reuse base::FileDescriptorWatcher for
953 // listening to EPOLLHUP.
954 struct epoll_event epevent;
955 epevent.events = EPOLLIN; // EPOLLERR | EPOLLHUP are always waited for.
956 epevent.data.fd = local_client_fd.get();
957 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_ADD,
958 local_client_fd.get(), &epevent) != 0) {
959 PLOG(ERROR) << "ConnectNamespaceResponse: epoll_ctl(EPOLL_CTL_ADD) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900960 datapath_->RemoveInterface(host_ifname);
961 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
962 subnet->Netmask());
963 datapath_->RemoveOutboundIPv4(host_ifname);
964 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900965 datapath_->NetnsDeleteName(netns_name);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900966 return;
967 }
968
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900969 // Prepare the response before storing ConnectNamespaceInfo.
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900970 response.set_peer_ifname(client_ifname);
971 response.set_peer_ipv4_address(host_ipv4_addr);
972 response.set_host_ifname(host_ifname);
973 response.set_host_ipv4_address(client_ipv4_addr);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900974 auto* response_subnet = response.mutable_ipv4_subnet();
975 response_subnet->set_base_addr(subnet->BaseAddress());
976 response_subnet->set_prefix_len(subnet->PrefixLength());
977
978 // Store ConnectNamespaceInfo
979 connected_namespaces_next_id_++;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900980 int fdkey = local_client_fd.release();
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900981 connected_namespaces_[fdkey] = {};
982 ConnectNamespaceInfo& ns_info = connected_namespaces_[fdkey];
983 ns_info.pid = request.pid();
Hugo Benichi33860d72020-07-09 16:34:01 +0900984 ns_info.netns_name = std::move(netns_name);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900985 ns_info.outbound_ifname = request.outbound_physical_device();
986 ns_info.host_ifname = std::move(host_ifname);
987 ns_info.client_ifname = std::move(client_ifname);
988 ns_info.client_subnet = std::move(subnet);
989
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900990 LOG(INFO) << "Connected network namespace " << ns_info;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900991
992 if (connected_namespaces_.size() == 1) {
993 LOG(INFO) << "Starting ConnectNamespace client fds monitoring";
994 CheckConnectedNamespaces();
995 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900996}
997
998void Manager::DisconnectNamespace(int client_fd) {
999 auto it = connected_namespaces_.find(client_fd);
1000 if (it == connected_namespaces_.end()) {
1001 LOG(ERROR) << "No ConnectNamespaceInfo found for client_fd " << client_fd;
1002 return;
1003 }
1004
Hugo Benichi7352ad92020-04-07 16:11:59 +09001005 // Remove the client fd dupe from the epoll watcher and close it.
1006 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL, client_fd,
Hugo Benichie8758b52020-04-03 14:49:01 +09001007 nullptr) != 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +09001008 PLOG(ERROR) << "DisconnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +09001009 if (close(client_fd) < 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +09001010 PLOG(ERROR) << "DisconnectNamespace: close(client_fd) failed";
Hugo Benichi7352ad92020-04-07 16:11:59 +09001011
Hugo Benichie8758b52020-04-03 14:49:01 +09001012 // Destroy the interface configuration and routing configuration:
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001013 // - destroy veth pair.
Hugo Benichie8758b52020-04-03 14:49:01 +09001014 // - remove forwarding rules on host namespace.
1015 // - remove SNAT marking rule on host namespace.
Hugo Benichi33860d72020-07-09 16:34:01 +09001016 // Delete the network namespace attached to the client namespace.
Hugo Benichie8758b52020-04-03 14:49:01 +09001017 // Note that the default route set inside the client namespace by patchpanel
1018 // is not destroyed: it is assumed the client will also teardown its
1019 // namespace if it triggered DisconnectNamespace.
1020 datapath_->RemoveInterface(it->second.host_ifname);
1021 datapath_->RemoveOutboundIPv4(it->second.host_ifname);
1022 datapath_->RemoveOutboundIPv4SNATMark(it->second.host_ifname);
1023 datapath_->DeleteIPv4Route(it->second.client_subnet->AddressAtOffset(0),
1024 it->second.client_subnet->BaseAddress(),
1025 it->second.client_subnet->Netmask());
Hugo Benichi33860d72020-07-09 16:34:01 +09001026 datapath_->NetnsDeleteName(it->second.netns_name);
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001027
1028 LOG(INFO) << "Disconnected network namespace " << it->second;
1029
1030 // This release the allocated IPv4 subnet.
1031 connected_namespaces_.erase(it);
1032}
1033
Hugo Benichi7352ad92020-04-07 16:11:59 +09001034// TODO(hugobenichi) Generalize this check to all resources created by
1035// patchpanel on behalf of a remote client.
1036void Manager::CheckConnectedNamespaces() {
1037 int max_event = 10;
1038 struct epoll_event epevents[max_event];
1039 int nready = epoll_wait(connected_namespaces_epollfd_, epevents, max_event,
1040 0 /* do not block */);
1041 if (nready < 0)
1042 PLOG(ERROR) << "CheckConnectedNamespaces: epoll_wait(0) failed";
1043
1044 for (int i = 0; i < nready; i++)
1045 if (epevents[i].events & (EPOLLHUP | EPOLLERR))
1046 DisconnectNamespace(epevents[i].data.fd);
1047
1048 if (connected_namespaces_.empty()) {
1049 LOG(INFO) << "Stopping ConnectNamespace client fds monitoring";
1050 return;
1051 }
1052
Qijiang Fan2d7aeb42020-05-19 02:06:39 +09001053 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Hugo Benichi7352ad92020-04-07 16:11:59 +09001054 FROM_HERE,
1055 base::Bind(&Manager::CheckConnectedNamespaces,
Hugo Benichie8758b52020-04-03 14:49:01 +09001056 weak_factory_.GetWeakPtr()),
Hugo Benichi7352ad92020-04-07 16:11:59 +09001057 kConnectNamespaceCheckInterval);
1058}
1059
Jason Jeremy Imanc28df852020-07-11 17:38:26 +09001060bool Manager::ModifyPortRule(const patchpanel::ModifyPortRuleRequest& request) {
1061 switch (request.proto()) {
1062 case patchpanel::ModifyPortRuleRequest::TCP:
1063 case patchpanel::ModifyPortRuleRequest::UDP:
1064 break;
1065 default:
1066 LOG(ERROR) << "Unknown protocol " << request.proto();
1067 return false;
1068 }
1069
1070 switch (request.op()) {
1071 case patchpanel::ModifyPortRuleRequest::CREATE:
1072 switch (request.type()) {
1073 case patchpanel::ModifyPortRuleRequest::ACCESS:
1074 return firewall_.AddAcceptRules(request.proto(),
1075 request.input_dst_port(),
1076 request.input_ifname());
1077 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
1078 return firewall_.AddLoopbackLockdownRules(request.proto(),
1079 request.input_dst_port());
1080 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1081 return firewall_.AddIpv4ForwardRule(
1082 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1083 request.input_ifname(), request.dst_ip(), request.dst_port());
1084 default:
1085 LOG(ERROR) << "Unknown port rule type " << request.type();
1086 return false;
1087 }
1088 case patchpanel::ModifyPortRuleRequest::DELETE:
1089 switch (request.type()) {
1090 case patchpanel::ModifyPortRuleRequest::ACCESS:
1091 return firewall_.DeleteAcceptRules(request.proto(),
1092 request.input_dst_port(),
1093 request.input_ifname());
1094 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
1095 return firewall_.DeleteLoopbackLockdownRules(
1096 request.proto(), request.input_dst_port());
1097 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1098 return firewall_.DeleteIpv4ForwardRule(
1099 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1100 request.input_ifname(), request.dst_ip(), request.dst_port());
1101 default:
1102 LOG(ERROR) << "Unknown port rule type " << request.type();
1103 return false;
1104 }
1105 default:
1106 LOG(ERROR) << "Unknown operation " << request.op();
1107 return false;
1108 }
1109}
1110
Garrick Evanse94a14e2019-11-11 10:32:13 +09001111void Manager::SendGuestMessage(const GuestMessage& msg) {
Garrick Evans96e03042019-05-28 14:30:52 +09001112 IpHelperMessage ipm;
1113 *ipm.mutable_guest_message() = msg;
Garrick Evans96e03042019-05-28 14:30:52 +09001114 adb_proxy_->SendMessage(ipm);
Garrick Evanse94a14e2019-11-11 10:32:13 +09001115 mcast_proxy_->SendMessage(ipm);
1116 nd_proxy_->SendMessage(ipm);
Garrick Evans96e03042019-05-28 14:30:52 +09001117}
1118
Garrick Evans4ac09852020-01-16 14:09:22 +09001119void Manager::StartForwarding(const std::string& ifname_physical,
1120 const std::string& ifname_virtual,
Garrick Evans4ac09852020-01-16 14:09:22 +09001121 bool ipv6,
1122 bool multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001123 if (ifname_physical.empty() || ifname_virtual.empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001124 return;
1125
1126 IpHelperMessage ipm;
1127 DeviceMessage* msg = ipm.mutable_device_message();
1128 msg->set_dev_ifname(ifname_physical);
Garrick Evans4ac09852020-01-16 14:09:22 +09001129 msg->set_br_ifname(ifname_virtual);
1130
1131 if (ipv6) {
1132 LOG(INFO) << "Starting IPv6 forwarding from " << ifname_physical << " to "
1133 << ifname_virtual;
1134
1135 if (!datapath_->AddIPv6Forwarding(ifname_physical, ifname_virtual)) {
1136 LOG(ERROR) << "Failed to setup iptables forwarding rule for IPv6 from "
1137 << ifname_physical << " to " << ifname_virtual;
1138 }
1139 if (!datapath_->MaskInterfaceFlags(ifname_physical, IFF_ALLMULTI)) {
1140 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1141 << ifname_physical;
1142 }
1143 if (!datapath_->MaskInterfaceFlags(ifname_virtual, IFF_ALLMULTI)) {
1144 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1145 << ifname_virtual;
1146 }
1147 nd_proxy_->SendMessage(ipm);
1148 }
1149
1150 if (multicast) {
1151 LOG(INFO) << "Starting multicast forwarding from " << ifname_physical
1152 << " to " << ifname_virtual;
1153 mcast_proxy_->SendMessage(ipm);
1154 }
1155}
1156
1157void Manager::StopForwarding(const std::string& ifname_physical,
1158 const std::string& ifname_virtual,
1159 bool ipv6,
1160 bool multicast) {
1161 if (ifname_physical.empty())
1162 return;
1163
1164 IpHelperMessage ipm;
1165 DeviceMessage* msg = ipm.mutable_device_message();
1166 msg->set_dev_ifname(ifname_physical);
1167 msg->set_teardown(true);
Taoyu Li7dca19a2020-03-16 16:27:07 +09001168 if (!ifname_virtual.empty()) {
1169 msg->set_br_ifname(ifname_virtual);
1170 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001171
1172 if (ipv6) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001173 if (ifname_virtual.empty()) {
1174 LOG(INFO) << "Stopping IPv6 forwarding on " << ifname_physical;
1175 } else {
1176 LOG(INFO) << "Stopping IPv6 forwarding from " << ifname_physical << " to "
1177 << ifname_virtual;
1178 datapath_->RemoveIPv6Forwarding(ifname_physical, ifname_virtual);
1179 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001180 nd_proxy_->SendMessage(ipm);
1181 }
1182
1183 if (multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001184 if (ifname_virtual.empty()) {
1185 LOG(INFO) << "Stopping multicast forwarding on " << ifname_physical;
1186 } else {
1187 LOG(INFO) << "Stopping multicast forwarding from " << ifname_physical
1188 << " to " << ifname_virtual;
1189 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001190 mcast_proxy_->SendMessage(ipm);
1191 }
1192}
1193
Taoyu Lia0727dc2020-09-24 19:54:59 +09001194void Manager::OnNDProxyMessage(const NDProxyMessage& msg) {
1195 LOG_IF(DFATAL, msg.ifname().empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001196 << "Received DeviceMessage w/ empty dev_ifname";
Taoyu Lia0727dc2020-09-24 19:54:59 +09001197 switch (msg.type()) {
1198 case NDProxyMessage::ADD_ROUTE:
1199 if (!datapath_->AddIPv6HostRoute(msg.ifname(), msg.ip6addr(), 128)) {
1200 LOG(WARNING) << "Failed to setup the IPv6 route for interface "
1201 << msg.ifname() << ", addr " << msg.ip6addr();
1202 }
1203 break;
1204 case NDProxyMessage::ADD_ADDR:
1205 if (!datapath_->AddIPv6Address(msg.ifname(), msg.ip6addr())) {
1206 LOG(WARNING) << "Failed to setup the IPv6 address for interface "
1207 << msg.ifname() << ", addr " << msg.ip6addr();
1208 }
1209 break;
1210 case NDProxyMessage::DEL_ADDR:
1211 datapath_->RemoveIPv6Address(msg.ifname(), msg.ip6addr());
1212 break;
1213 default:
1214 LOG(ERROR) << "Unknown NDProxy event " << msg.type();
1215 NOTREACHED();
Garrick Evans4ac09852020-01-16 14:09:22 +09001216 }
1217}
1218
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001219std::ostream& operator<<(std::ostream& stream,
1220 const Manager::ConnectNamespaceInfo& ns_info) {
1221 stream << "{ pid: " << ns_info.pid;
1222 if (!ns_info.outbound_ifname.empty()) {
1223 stream << ", outbound_ifname: " << ns_info.outbound_ifname;
1224 }
1225 stream << ", host_ifname: " << ns_info.host_ifname
1226 << ", client_ifname: " << ns_info.client_ifname
1227 << ", subnet: " << ns_info.client_subnet->ToCidrString() << '}';
1228 return stream;
1229}
1230
Garrick Evans3388a032020-03-24 11:25:55 +09001231} // namespace patchpanel