blob: 4f7a7c079a4979ddf43880c8ac37ebfeb103712f [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 Evans02e6e872020-11-30 11:53:13 +0900199 {patchpanel::kGetDevicesMethod, &Manager::OnGetDevices},
Garrick Evans08843932019-09-17 14:41:08 +0900200 };
201
202 for (const auto& kv : kServiceMethods) {
203 if (!dbus_svc_path_->ExportMethodAndBlock(
204 patchpanel::kPatchPanelInterface, kv.first,
205 base::Bind(&HandleSynchronousDBusMethodCall,
206 base::Bind(kv.second, base::Unretained(this))))) {
207 LOG(FATAL) << "Failed to export method " << kv.first;
208 }
209 }
210
211 if (!bus_->RequestOwnershipAndBlock(patchpanel::kPatchPanelServiceName,
212 dbus::Bus::REQUIRE_PRIMARY)) {
213 LOG(FATAL) << "Failed to take ownership of "
214 << patchpanel::kPatchPanelServiceName;
215 }
216 LOG(INFO) << "DBus service interface ready";
217
Hugo Benichifda77232020-08-21 18:28:15 +0900218 routing_svc_ = std::make_unique<RoutingService>();
219
Hugo Benichibf811c62020-09-07 17:30:45 +0900220 // b/162966185: Allow Jetstream to disable:
221 // - the IP forwarding setup used for hosting VMs and containers,
222 // - the iptables rules for fwmark based routing.
223 if (!USE_JETSTREAM_ROUTING) {
224 datapath_->Start();
Hugo Benichi2a940542020-10-26 18:50:49 +0900225 shill_client_->RegisterDefaultDeviceChangedHandler(base::BindRepeating(
226 &Manager::OnDefaultDeviceChanged, weak_factory_.GetWeakPtr()));
Hugo Benichibf811c62020-09-07 17:30:45 +0900227 shill_client_->RegisterDevicesChangedHandler(base::BindRepeating(
228 &Manager::OnDevicesChanged, weak_factory_.GetWeakPtr()));
229 }
Hugo Benichifda77232020-08-21 18:28:15 +0900230
Taoyu Lia0727dc2020-09-24 19:54:59 +0900231 nd_proxy_->RegisterNDProxyMessageHandler(
232 base::Bind(&Manager::OnNDProxyMessage, weak_factory_.GetWeakPtr()));
Hugo Benichifda77232020-08-21 18:28:15 +0900233
Hugo Benichifda77232020-08-21 18:28:15 +0900234 auto* const forwarder = static_cast<TrafficForwarder*>(this);
235
236 GuestMessage::GuestType arc_guest =
237 USE_ARCVM ? GuestMessage::ARC_VM : GuestMessage::ARC;
238 arc_svc_ = std::make_unique<ArcService>(shill_client_.get(), datapath_.get(),
239 &addr_mgr_, forwarder, arc_guest);
240 cros_svc_ = std::make_unique<CrostiniService>(shill_client_.get(), &addr_mgr_,
241 datapath_.get(), forwarder);
Jie Jiang84966852020-09-18 18:49:05 +0900242 network_monitor_svc_ = std::make_unique<NetworkMonitorService>(
243 shill_client_.get(),
Jie Jiang25c1b972020-11-12 15:42:53 +0900244 base::BindRepeating(&Manager::OnNeighborReachabilityEvent,
Jie Jiang84966852020-09-18 18:49:05 +0900245 weak_factory_.GetWeakPtr()));
Hugo Benichifda77232020-08-21 18:28:15 +0900246 network_monitor_svc_->Start();
247
248 counters_svc_ =
249 std::make_unique<CountersService>(shill_client_.get(), runner_.get());
250
251 nd_proxy_->Listen();
252}
253
254void Manager::OnShutdown(int* exit_code) {
255 LOG(INFO) << "Shutting down and cleaning up";
Jie Jiang84966852020-09-18 18:49:05 +0900256 network_monitor_svc_.reset();
Hugo Benichifda77232020-08-21 18:28:15 +0900257 cros_svc_.reset();
258 arc_svc_.reset();
259 close(connected_namespaces_epollfd_);
260 // Tear down any remaining connected namespace.
261 std::vector<int> connected_namespaces_fdkeys;
262 for (const auto& kv : connected_namespaces_)
263 connected_namespaces_fdkeys.push_back(kv.first);
264 for (const int fdkey : connected_namespaces_fdkeys)
265 DisconnectNamespace(fdkey);
Hugo Benichibf811c62020-09-07 17:30:45 +0900266 if (!USE_JETSTREAM_ROUTING)
267 datapath_->Stop();
Hugo Benichifda77232020-08-21 18:28:15 +0900268}
269
270void Manager::OnSubprocessExited(pid_t pid, const siginfo_t&) {
271 LOG(ERROR) << "Subprocess " << pid << " exited unexpectedly -"
272 << " attempting to restart";
273
274 HelperProcess* proc;
275 if (pid == adb_proxy_->pid()) {
276 proc = adb_proxy_.get();
277 } else if (pid == mcast_proxy_->pid()) {
278 proc = mcast_proxy_.get();
279 } else if (pid == nd_proxy_->pid()) {
280 proc = nd_proxy_.get();
281 } else {
282 LOG(DFATAL) << "Unknown child process";
283 return;
284 }
285
286 process_reaper_.ForgetChild(pid);
287
288 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
289 FROM_HERE,
290 base::Bind(&Manager::RestartSubprocess, weak_factory_.GetWeakPtr(), proc),
291 base::TimeDelta::FromMilliseconds((2 << proc->restarts()) *
292 kSubprocessRestartDelayMs));
293}
294
295void Manager::RestartSubprocess(HelperProcess* subproc) {
296 if (subproc->Restart()) {
297 DCHECK(process_reaper_.WatchForChild(
298 FROM_HERE, subproc->pid(),
299 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
300 subproc->pid())))
301 << "Failed to watch child process " << subproc->pid();
302 }
303}
304
Hugo Benichi2a940542020-10-26 18:50:49 +0900305void Manager::OnDefaultDeviceChanged(const ShillClient::Device& new_device,
306 const ShillClient::Device& prev_device) {
307 // Only take into account interface switches and ignore layer 3 property
308 // changes.
309 if (prev_device.ifname == new_device.ifname)
310 return;
311
312 if (prev_device.type == ShillClient::Device::Type::kVPN)
313 datapath_->StopVpnRouting(prev_device.ifname);
314
315 if (new_device.type == ShillClient::Device::Type::kVPN)
316 datapath_->StartVpnRouting(new_device.ifname);
317}
318
Hugo Benichi76be34a2020-08-26 22:35:54 +0900319void Manager::OnDevicesChanged(const std::set<std::string>& added,
320 const std::set<std::string>& removed) {
321 for (const std::string& ifname : removed)
322 datapath_->StopConnectionPinning(ifname);
323
324 for (const std::string& ifname : added)
325 datapath_->StartConnectionPinning(ifname);
326}
327
Garrick Evanse94a14e2019-11-11 10:32:13 +0900328bool Manager::StartArc(pid_t pid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900329 if (!arc_svc_->Start(pid))
330 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900331
332 GuestMessage msg;
333 msg.set_event(GuestMessage::START);
334 msg.set_type(GuestMessage::ARC);
335 msg.set_arc_pid(pid);
336 SendGuestMessage(msg);
337
338 return true;
339}
340
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900341void Manager::StopArc() {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900342 GuestMessage msg;
343 msg.set_event(GuestMessage::STOP);
344 msg.set_type(GuestMessage::ARC);
345 SendGuestMessage(msg);
346
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900347 // After the ARC container has stopped, the pid is not known anymore.
348 // The pid argument is ignored by ArcService.
349 arc_svc_->Stop(0);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900350}
351
Garrick Evans015b0d62020-02-07 09:06:38 +0900352bool Manager::StartArcVm(uint32_t cid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900353 if (!arc_svc_->Start(cid))
354 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900355
356 GuestMessage msg;
357 msg.set_event(GuestMessage::START);
358 msg.set_type(GuestMessage::ARC_VM);
359 msg.set_arcvm_vsock_cid(cid);
360 SendGuestMessage(msg);
361
362 return true;
363}
364
Garrick Evans015b0d62020-02-07 09:06:38 +0900365void Manager::StopArcVm(uint32_t cid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900366 GuestMessage msg;
367 msg.set_event(GuestMessage::STOP);
368 msg.set_type(GuestMessage::ARC_VM);
369 SendGuestMessage(msg);
370
Garrick Evans21173b12019-11-20 15:23:16 +0900371 arc_svc_->Stop(cid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900372}
373
Garrick Evans51d5b552020-01-30 10:42:06 +0900374bool Manager::StartCrosVm(uint64_t vm_id,
375 GuestMessage::GuestType vm_type,
Garrick Evans53a2a982020-02-05 10:53:35 +0900376 uint32_t subnet_index) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900377 DCHECK(vm_type == GuestMessage::TERMINA_VM ||
378 vm_type == GuestMessage::PLUGIN_VM);
379
380 if (!cros_svc_->Start(vm_id, vm_type == GuestMessage::TERMINA_VM,
381 subnet_index))
Garrick Evans47c19272019-11-21 10:58:21 +0900382 return false;
383
384 GuestMessage msg;
385 msg.set_event(GuestMessage::START);
Garrick Evans51d5b552020-01-30 10:42:06 +0900386 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900387 SendGuestMessage(msg);
388
389 return true;
390}
391
Garrick Evans51d5b552020-01-30 10:42:06 +0900392void Manager::StopCrosVm(uint64_t vm_id, GuestMessage::GuestType vm_type) {
Garrick Evans47c19272019-11-21 10:58:21 +0900393 GuestMessage msg;
394 msg.set_event(GuestMessage::STOP);
Garrick Evans51d5b552020-01-30 10:42:06 +0900395 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900396 SendGuestMessage(msg);
397
Garrick Evans51d5b552020-01-30 10:42:06 +0900398 cros_svc_->Stop(vm_id, vm_type == GuestMessage::TERMINA_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900399}
400
Garrick Evans02e6e872020-11-30 11:53:13 +0900401std::unique_ptr<dbus::Response> Manager::OnGetDevices(
402 dbus::MethodCall* method_call) {
403 std::unique_ptr<dbus::Response> dbus_response(
404 dbus::Response::FromMethodCall(method_call));
405
406 dbus::MessageReader reader(method_call);
407 dbus::MessageWriter writer(dbus_response.get());
408
409 patchpanel::GetDevicesRequest request;
410 patchpanel::GetDevicesResponse response;
411
412 if (!reader.PopArrayOfBytesAsProto(&request)) {
413 LOG(ERROR) << "Unable to parse request";
414 writer.AppendProtoAsArrayOfBytes(response);
415 return dbus_response;
416 }
417
418 static const auto arc_guest_type =
419 USE_ARCVM ? NetworkDevice::ARCVM : NetworkDevice::ARC;
420
421 arc_svc_->ScanDevices(base::BindRepeating(
422 [](patchpanel::GetDevicesResponse* resp, const Device& device) {
423 auto* dev = resp->add_devices();
424 dev->set_ifname(device.host_ifname());
425 dev->set_ipv4_addr(device.config().guest_ipv4_addr());
426 dev->set_guest_type(arc_guest_type);
427 if (const auto* subnet = device.config().ipv4_subnet()) {
428 auto* sub = dev->mutable_ipv4_subnet();
429 sub->set_base_addr(subnet->BaseAddress());
430 sub->set_prefix_len(subnet->PrefixLength());
431 }
432 },
433 &response));
434
435 cros_svc_->ScanDevices(base::BindRepeating(
436 [](patchpanel::GetDevicesResponse* resp, uint64_t vm_id, bool is_termina,
437 const Device& device) {
438 auto* dev = resp->add_devices();
439 dev->set_ifname(device.host_ifname());
440 dev->set_ipv4_addr(device.config().guest_ipv4_addr());
441 dev->set_guest_type(is_termina ? NetworkDevice::TERMINA_VM
442 : NetworkDevice::PLUGIN_VM);
443 if (const auto* subnet = device.config().ipv4_subnet()) {
444 auto* sub = dev->mutable_ipv4_subnet();
445 sub->set_base_addr(subnet->BaseAddress());
446 sub->set_prefix_len(subnet->PrefixLength());
447 }
448 },
449 &response));
450
451 writer.AppendProtoAsArrayOfBytes(response);
452 return dbus_response;
453}
454
Garrick Evans08843932019-09-17 14:41:08 +0900455std::unique_ptr<dbus::Response> Manager::OnArcStartup(
456 dbus::MethodCall* method_call) {
457 LOG(INFO) << "ARC++ starting up";
458
459 std::unique_ptr<dbus::Response> dbus_response(
460 dbus::Response::FromMethodCall(method_call));
461
462 dbus::MessageReader reader(method_call);
463 dbus::MessageWriter writer(dbus_response.get());
464
465 patchpanel::ArcStartupRequest request;
466 patchpanel::ArcStartupResponse response;
467
468 if (!reader.PopArrayOfBytesAsProto(&request)) {
469 LOG(ERROR) << "Unable to parse request";
470 writer.AppendProtoAsArrayOfBytes(response);
471 return dbus_response;
472 }
473
Garrick Evanse01bf072019-11-15 09:08:19 +0900474 if (!StartArc(request.pid()))
475 LOG(ERROR) << "Failed to start ARC++ network service";
Garrick Evanse94a14e2019-11-11 10:32:13 +0900476
Garrick Evans08843932019-09-17 14:41:08 +0900477 writer.AppendProtoAsArrayOfBytes(response);
478 return dbus_response;
479}
480
481std::unique_ptr<dbus::Response> Manager::OnArcShutdown(
482 dbus::MethodCall* method_call) {
483 LOG(INFO) << "ARC++ shutting down";
484
485 std::unique_ptr<dbus::Response> dbus_response(
486 dbus::Response::FromMethodCall(method_call));
487
488 dbus::MessageReader reader(method_call);
489 dbus::MessageWriter writer(dbus_response.get());
490
491 patchpanel::ArcShutdownRequest request;
492 patchpanel::ArcShutdownResponse response;
493
494 if (!reader.PopArrayOfBytesAsProto(&request)) {
495 LOG(ERROR) << "Unable to parse request";
496 writer.AppendProtoAsArrayOfBytes(response);
497 return dbus_response;
498 }
499
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900500 StopArc();
Garrick Evanse94a14e2019-11-11 10:32:13 +0900501
Garrick Evans08843932019-09-17 14:41:08 +0900502 writer.AppendProtoAsArrayOfBytes(response);
503 return dbus_response;
504}
505
506std::unique_ptr<dbus::Response> Manager::OnArcVmStartup(
507 dbus::MethodCall* method_call) {
508 LOG(INFO) << "ARCVM starting up";
509
510 std::unique_ptr<dbus::Response> dbus_response(
511 dbus::Response::FromMethodCall(method_call));
512
513 dbus::MessageReader reader(method_call);
514 dbus::MessageWriter writer(dbus_response.get());
515
516 patchpanel::ArcVmStartupRequest request;
517 patchpanel::ArcVmStartupResponse response;
518
519 if (!reader.PopArrayOfBytesAsProto(&request)) {
520 LOG(ERROR) << "Unable to parse request";
521 writer.AppendProtoAsArrayOfBytes(response);
522 return dbus_response;
523 }
524
Garrick Evans47c19272019-11-21 10:58:21 +0900525 if (!StartArcVm(request.cid())) {
Garrick Evanse01bf072019-11-15 09:08:19 +0900526 LOG(ERROR) << "Failed to start ARCVM network service";
Garrick Evans47c19272019-11-21 10:58:21 +0900527 writer.AppendProtoAsArrayOfBytes(response);
528 return dbus_response;
Garrick Evanse01bf072019-11-15 09:08:19 +0900529 }
Garrick Evanse94a14e2019-11-11 10:32:13 +0900530
Garrick Evans47c19272019-11-21 10:58:21 +0900531 // Populate the response with the known devices.
Garrick Evans38b25a42020-04-06 15:17:42 +0900532 for (const auto* config : arc_svc_->GetDeviceConfigs()) {
533 if (config->tap_ifname().empty())
534 continue;
Garrick Evans47c19272019-11-21 10:58:21 +0900535
Garrick Evans38b25a42020-04-06 15:17:42 +0900536 auto* dev = response.add_devices();
537 dev->set_ifname(config->tap_ifname());
538 dev->set_ipv4_addr(config->guest_ipv4_addr());
Garrick Evansa0c9c972020-11-30 09:54:59 +0900539 dev->set_guest_type(NetworkDevice::ARCVM);
Garrick Evans38b25a42020-04-06 15:17:42 +0900540 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900541
Garrick Evans08843932019-09-17 14:41:08 +0900542 writer.AppendProtoAsArrayOfBytes(response);
543 return dbus_response;
544}
545
546std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
547 dbus::MethodCall* method_call) {
548 LOG(INFO) << "ARCVM shutting down";
549
550 std::unique_ptr<dbus::Response> dbus_response(
551 dbus::Response::FromMethodCall(method_call));
552
553 dbus::MessageReader reader(method_call);
554 dbus::MessageWriter writer(dbus_response.get());
555
556 patchpanel::ArcVmShutdownRequest request;
557 patchpanel::ArcVmShutdownResponse response;
558
559 if (!reader.PopArrayOfBytesAsProto(&request)) {
560 LOG(ERROR) << "Unable to parse request";
561 writer.AppendProtoAsArrayOfBytes(response);
562 return dbus_response;
563 }
564
Garrick Evans21173b12019-11-20 15:23:16 +0900565 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900566
Garrick Evans08843932019-09-17 14:41:08 +0900567 writer.AppendProtoAsArrayOfBytes(response);
568 return dbus_response;
569}
570
Garrick Evans47c19272019-11-21 10:58:21 +0900571std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
572 dbus::MethodCall* method_call) {
573 LOG(INFO) << "Termina VM starting up";
574
575 std::unique_ptr<dbus::Response> dbus_response(
576 dbus::Response::FromMethodCall(method_call));
577
578 dbus::MessageReader reader(method_call);
579 dbus::MessageWriter writer(dbus_response.get());
580
581 patchpanel::TerminaVmStartupRequest request;
582 patchpanel::TerminaVmStartupResponse response;
583
584 if (!reader.PopArrayOfBytesAsProto(&request)) {
585 LOG(ERROR) << "Unable to parse request";
586 writer.AppendProtoAsArrayOfBytes(response);
587 return dbus_response;
588 }
589
590 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900591 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900592 LOG(ERROR) << "Failed to start Termina VM network service";
593 writer.AppendProtoAsArrayOfBytes(response);
594 return dbus_response;
595 }
596
Garrick Evans51d5b552020-01-30 10:42:06 +0900597 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900598 if (!tap) {
599 LOG(DFATAL) << "TAP device missing";
600 writer.AppendProtoAsArrayOfBytes(response);
601 return dbus_response;
602 }
Garrick Evans47c19272019-11-21 10:58:21 +0900603
Garrick Evansb1c93712020-01-22 09:28:25 +0900604 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900605 dev->set_ifname(tap->host_ifname());
Garrick Evansa0c9c972020-11-30 09:54:59 +0900606 dev->set_guest_type(NetworkDevice::TERMINA_VM);
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900607 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900608 if (!subnet) {
609 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
610 writer.AppendProtoAsArrayOfBytes(response);
611 return dbus_response;
612 }
613 auto* resp_subnet = dev->mutable_ipv4_subnet();
614 resp_subnet->set_base_addr(subnet->BaseAddress());
615 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900616 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900617 if (!subnet) {
618 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
619 writer.AppendProtoAsArrayOfBytes(response);
620 return dbus_response;
621 }
622 resp_subnet = response.mutable_container_subnet();
623 resp_subnet->set_base_addr(subnet->BaseAddress());
624 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900625
626 writer.AppendProtoAsArrayOfBytes(response);
627 return dbus_response;
628}
629
630std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
631 dbus::MethodCall* method_call) {
632 LOG(INFO) << "Termina VM shutting down";
633
634 std::unique_ptr<dbus::Response> dbus_response(
635 dbus::Response::FromMethodCall(method_call));
636
637 dbus::MessageReader reader(method_call);
638 dbus::MessageWriter writer(dbus_response.get());
639
640 patchpanel::TerminaVmShutdownRequest request;
641 patchpanel::TerminaVmShutdownResponse response;
642
643 if (!reader.PopArrayOfBytesAsProto(&request)) {
644 LOG(ERROR) << "Unable to parse request";
645 writer.AppendProtoAsArrayOfBytes(response);
646 return dbus_response;
647 }
648
Garrick Evans51d5b552020-01-30 10:42:06 +0900649 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
650
651 writer.AppendProtoAsArrayOfBytes(response);
652 return dbus_response;
653}
654
655std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
656 dbus::MethodCall* method_call) {
657 LOG(INFO) << "Plugin VM starting up";
658
659 std::unique_ptr<dbus::Response> dbus_response(
660 dbus::Response::FromMethodCall(method_call));
661
662 dbus::MessageReader reader(method_call);
663 dbus::MessageWriter writer(dbus_response.get());
664
665 patchpanel::PluginVmStartupRequest request;
666 patchpanel::PluginVmStartupResponse response;
667
668 if (!reader.PopArrayOfBytesAsProto(&request)) {
669 LOG(ERROR) << "Unable to parse request";
670 writer.AppendProtoAsArrayOfBytes(response);
671 return dbus_response;
672 }
673
Garrick Evans08fb34b2020-02-20 10:50:17 +0900674 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900675 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900676 LOG(ERROR) << "Failed to start Plugin VM network service";
677 writer.AppendProtoAsArrayOfBytes(response);
678 return dbus_response;
679 }
680
681 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
682 if (!tap) {
683 LOG(DFATAL) << "TAP device missing";
684 writer.AppendProtoAsArrayOfBytes(response);
685 return dbus_response;
686 }
687
Garrick Evans51d5b552020-01-30 10:42:06 +0900688 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900689 dev->set_ifname(tap->host_ifname());
Garrick Evansa0c9c972020-11-30 09:54:59 +0900690 dev->set_guest_type(NetworkDevice::PLUGIN_VM);
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900691 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900692 if (!subnet) {
693 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
694 writer.AppendProtoAsArrayOfBytes(response);
695 return dbus_response;
696 }
697 auto* resp_subnet = dev->mutable_ipv4_subnet();
698 resp_subnet->set_base_addr(subnet->BaseAddress());
699 resp_subnet->set_prefix_len(subnet->PrefixLength());
700
701 writer.AppendProtoAsArrayOfBytes(response);
702 return dbus_response;
703}
704
705std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
706 dbus::MethodCall* method_call) {
707 LOG(INFO) << "Plugin VM shutting down";
708
709 std::unique_ptr<dbus::Response> dbus_response(
710 dbus::Response::FromMethodCall(method_call));
711
712 dbus::MessageReader reader(method_call);
713 dbus::MessageWriter writer(dbus_response.get());
714
715 patchpanel::PluginVmShutdownRequest request;
716 patchpanel::PluginVmShutdownResponse response;
717
718 if (!reader.PopArrayOfBytesAsProto(&request)) {
719 LOG(ERROR) << "Unable to parse request";
720 writer.AppendProtoAsArrayOfBytes(response);
721 return dbus_response;
722 }
723
724 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900725
726 writer.AppendProtoAsArrayOfBytes(response);
727 return dbus_response;
728}
729
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900730std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
731 dbus::MethodCall* method_call) {
732 std::unique_ptr<dbus::Response> dbus_response(
733 dbus::Response::FromMethodCall(method_call));
734
735 dbus::MessageReader reader(method_call);
736 dbus::MessageWriter writer(dbus_response.get());
737
738 patchpanel::SetVpnIntentRequest request;
739 patchpanel::SetVpnIntentResponse response;
740
741 bool success = reader.PopArrayOfBytesAsProto(&request);
742 if (!success) {
743 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
744 // Do not return yet to make sure we close the received fd.
745 }
746
747 base::ScopedFD client_socket;
748 reader.PopFileDescriptor(&client_socket);
749
750 if (success)
751 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
752
753 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900754
755 writer.AppendProtoAsArrayOfBytes(response);
756 return dbus_response;
757}
758
759std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
760 dbus::MethodCall* method_call) {
761 std::unique_ptr<dbus::Response> dbus_response(
762 dbus::Response::FromMethodCall(method_call));
763
764 dbus::MessageReader reader(method_call);
765 dbus::MessageWriter writer(dbus_response.get());
766
767 patchpanel::ConnectNamespaceRequest request;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900768
769 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900770 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
771 // Do not return yet to make sure we close the received fd and
772 // validate other arguments.
Hugo Benichi7c342672020-09-08 09:18:14 +0900773 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
774 return dbus_response;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900775 }
776
Hugo Benichicc6850f2020-01-17 13:26:06 +0900777 base::ScopedFD client_fd;
778 reader.PopFileDescriptor(&client_fd);
779 if (!client_fd.is_valid()) {
780 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
Hugo Benichi7c342672020-09-08 09:18:14 +0900781 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
782 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900783 }
784
785 pid_t pid = request.pid();
786 {
787 ScopedNS ns(pid);
788 if (!ns.IsValid()) {
789 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900790 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
791 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900792 }
793 }
794
795 const std::string& outbound_ifname = request.outbound_physical_device();
796 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
797 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
798 << outbound_ifname;
Hugo Benichi7c342672020-09-08 09:18:14 +0900799 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
800 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900801 }
802
Hugo Benichi7c342672020-09-08 09:18:14 +0900803 auto response = ConnectNamespace(std::move(client_fd), request);
804 writer.AppendProtoAsArrayOfBytes(*response);
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900805 return dbus_response;
806}
807
Jie Jiang493cde42020-07-17 21:43:39 +0900808std::unique_ptr<dbus::Response> Manager::OnGetTrafficCounters(
809 dbus::MethodCall* method_call) {
810 std::unique_ptr<dbus::Response> dbus_response(
811 dbus::Response::FromMethodCall(method_call));
812
813 dbus::MessageReader reader(method_call);
814 dbus::MessageWriter writer(dbus_response.get());
815
816 patchpanel::TrafficCountersRequest request;
817 patchpanel::TrafficCountersResponse response;
818
819 if (!reader.PopArrayOfBytesAsProto(&request)) {
820 LOG(ERROR) << "Unable to parse TrafficCountersRequest";
821 writer.AppendProtoAsArrayOfBytes(response);
822 return dbus_response;
823 }
824
825 const std::set<std::string> devices{request.devices().begin(),
826 request.devices().end()};
827 const auto counters = counters_svc_->GetCounters(devices);
828 for (const auto& kv : counters) {
829 auto* traffic_counter = response.add_counters();
830 const auto& source_and_device = kv.first;
831 const auto& counter = kv.second;
832 traffic_counter->set_source(source_and_device.first);
833 traffic_counter->set_device(source_and_device.second);
834 traffic_counter->set_rx_bytes(counter.rx_bytes);
835 traffic_counter->set_rx_packets(counter.rx_packets);
836 traffic_counter->set_tx_bytes(counter.tx_bytes);
837 traffic_counter->set_tx_packets(counter.tx_packets);
838 }
839
840 writer.AppendProtoAsArrayOfBytes(response);
841 return dbus_response;
842}
843
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900844std::unique_ptr<dbus::Response> Manager::OnModifyPortRule(
845 dbus::MethodCall* method_call) {
846 std::unique_ptr<dbus::Response> dbus_response(
847 dbus::Response::FromMethodCall(method_call));
848
849 dbus::MessageReader reader(method_call);
850 dbus::MessageWriter writer(dbus_response.get());
851
852 patchpanel::ModifyPortRuleRequest request;
853 patchpanel::ModifyPortRuleResponse response;
854
855 if (!reader.PopArrayOfBytesAsProto(&request)) {
856 LOG(ERROR) << "Unable to parse ModifyPortRequest";
857 writer.AppendProtoAsArrayOfBytes(response);
858 return dbus_response;
859 }
860
Jason Jeremy Imanc28df852020-07-11 17:38:26 +0900861 response.set_success(ModifyPortRule(request));
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900862 writer.AppendProtoAsArrayOfBytes(response);
863 return dbus_response;
864}
865
Jie Jiang25c1b972020-11-12 15:42:53 +0900866void Manager::OnNeighborReachabilityEvent(
Jie Jiang84966852020-09-18 18:49:05 +0900867 int ifindex,
868 const shill::IPAddress& ip_addr,
869 NeighborLinkMonitor::NeighborRole role,
Jie Jiang25c1b972020-11-12 15:42:53 +0900870 NeighborReachabilityEventSignal::EventType event_type) {
Jie Jiang84966852020-09-18 18:49:05 +0900871 if (!ip_addr.IsValid()) {
872 LOG(DFATAL) << "ip_addr is not valid";
873 return;
874 }
875
Jie Jiang25c1b972020-11-12 15:42:53 +0900876 using SignalProto = NeighborReachabilityEventSignal;
Jie Jiang84966852020-09-18 18:49:05 +0900877 SignalProto proto;
878 proto.set_ifindex(ifindex);
879 proto.set_ip_addr(ip_addr.ToString());
Jie Jiang25c1b972020-11-12 15:42:53 +0900880 proto.set_type(event_type);
Jie Jiang84966852020-09-18 18:49:05 +0900881 switch (role) {
882 case NeighborLinkMonitor::NeighborRole::kGateway:
883 proto.set_role(SignalProto::GATEWAY);
884 break;
885 case NeighborLinkMonitor::NeighborRole::kDNSServer:
886 proto.set_role(SignalProto::DNS_SERVER);
887 break;
888 case NeighborLinkMonitor::NeighborRole::kGatewayAndDNSServer:
889 proto.set_role(SignalProto::GATEWAY_AND_DNS_SERVER);
890 break;
891 default:
892 NOTREACHED();
893 }
894
Jie Jiang25c1b972020-11-12 15:42:53 +0900895 dbus::Signal signal(kPatchPanelInterface, kNeighborReachabilityEventSignal);
Jie Jiang84966852020-09-18 18:49:05 +0900896 dbus::MessageWriter writer(&signal);
897 if (!writer.AppendProtoAsArrayOfBytes(proto)) {
Jie Jiang25c1b972020-11-12 15:42:53 +0900898 LOG(ERROR) << "Failed to encode proto NeighborReachabilityEventSignal";
Jie Jiang84966852020-09-18 18:49:05 +0900899 return;
900 }
901
902 dbus_svc_path_->SendSignal(&signal);
903}
904
Hugo Benichi7c342672020-09-08 09:18:14 +0900905std::unique_ptr<patchpanel::ConnectNamespaceResponse> Manager::ConnectNamespace(
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900906 base::ScopedFD client_fd,
Hugo Benichi7c342672020-09-08 09:18:14 +0900907 const patchpanel::ConnectNamespaceRequest& request) {
908 auto response = std::make_unique<patchpanel::ConnectNamespaceResponse>();
909
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900910 std::unique_ptr<Subnet> subnet =
911 addr_mgr_.AllocateIPv4Subnet(AddressManager::Guest::MINIJAIL_NETNS);
912 if (!subnet) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900913 LOG(ERROR) << "ConnectNamespace: exhausted IPv4 subnet space";
914 return response;
Hugo Benichie8758b52020-04-03 14:49:01 +0900915 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900916
Hugo Benichi7352ad92020-04-07 16:11:59 +0900917 // Dup the client fd into our own: this guarantees that the fd number will
918 // be stable and tied to the actual kernel resources used by the client.
919 base::ScopedFD local_client_fd(dup(client_fd.get()));
920 if (!local_client_fd.is_valid()) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900921 PLOG(ERROR) << "ConnectNamespace: failed to dup() client fd";
922 return response;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900923 }
924
Hugo Benichi7c342672020-09-08 09:18:14 +0900925 // Add the duped fd to the epoll watcher.
Hugo Benichi7352ad92020-04-07 16:11:59 +0900926 // TODO(hugobenichi) Find a way to reuse base::FileDescriptorWatcher for
927 // listening to EPOLLHUP.
928 struct epoll_event epevent;
929 epevent.events = EPOLLIN; // EPOLLERR | EPOLLHUP are always waited for.
930 epevent.data.fd = local_client_fd.get();
931 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_ADD,
932 local_client_fd.get(), &epevent) != 0) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900933 PLOG(ERROR) << "ConnectNamespace: epoll_ctl(EPOLL_CTL_ADD) failed";
934 return response;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900935 }
936
Hugo Benichi7c342672020-09-08 09:18:14 +0900937 const std::string ifname_id = std::to_string(connected_namespaces_next_id_);
938 const std::string netns_name = "connected_netns_" + ifname_id;
939 const std::string host_ifname = "arc_ns" + ifname_id;
940 const std::string client_ifname = "veth" + ifname_id;
941 if (!datapath_->StartRoutingNamespace(
942 request.pid(), netns_name, host_ifname, client_ifname,
943 subnet->BaseAddress(), subnet->PrefixLength(),
944 subnet->AddressAtOffset(0), subnet->AddressAtOffset(1),
945 addr_mgr_.GenerateMacAddress())) {
946 LOG(ERROR) << "ConnectNamespace: failed to setup datapath";
947 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL,
948 local_client_fd.get(), nullptr) != 0)
949 PLOG(ERROR) << "ConnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
950 return response;
951 }
952
953 // TODO(hugobenichi) The peer and host addresses are swapped in the response
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900954 // Prepare the response before storing ConnectNamespaceInfo.
Hugo Benichi7c342672020-09-08 09:18:14 +0900955 response->set_peer_ifname(client_ifname);
956 response->set_peer_ipv4_address(subnet->AddressAtOffset(0));
957 response->set_host_ifname(host_ifname);
958 response->set_host_ipv4_address(subnet->AddressAtOffset(1));
959 auto* response_subnet = response->mutable_ipv4_subnet();
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900960 response_subnet->set_base_addr(subnet->BaseAddress());
961 response_subnet->set_prefix_len(subnet->PrefixLength());
962
963 // Store ConnectNamespaceInfo
964 connected_namespaces_next_id_++;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900965 int fdkey = local_client_fd.release();
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900966 connected_namespaces_[fdkey] = {};
967 ConnectNamespaceInfo& ns_info = connected_namespaces_[fdkey];
968 ns_info.pid = request.pid();
Hugo Benichi33860d72020-07-09 16:34:01 +0900969 ns_info.netns_name = std::move(netns_name);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900970 ns_info.outbound_ifname = request.outbound_physical_device();
971 ns_info.host_ifname = std::move(host_ifname);
972 ns_info.client_ifname = std::move(client_ifname);
973 ns_info.client_subnet = std::move(subnet);
974
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900975 LOG(INFO) << "Connected network namespace " << ns_info;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900976
977 if (connected_namespaces_.size() == 1) {
978 LOG(INFO) << "Starting ConnectNamespace client fds monitoring";
979 CheckConnectedNamespaces();
980 }
Hugo Benichi7c342672020-09-08 09:18:14 +0900981
982 return response;
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900983}
984
985void Manager::DisconnectNamespace(int client_fd) {
986 auto it = connected_namespaces_.find(client_fd);
987 if (it == connected_namespaces_.end()) {
988 LOG(ERROR) << "No ConnectNamespaceInfo found for client_fd " << client_fd;
989 return;
990 }
991
Hugo Benichi7352ad92020-04-07 16:11:59 +0900992 // Remove the client fd dupe from the epoll watcher and close it.
993 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL, client_fd,
Hugo Benichie8758b52020-04-03 14:49:01 +0900994 nullptr) != 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900995 PLOG(ERROR) << "DisconnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900996 if (close(client_fd) < 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900997 PLOG(ERROR) << "DisconnectNamespace: close(client_fd) failed";
Hugo Benichi7352ad92020-04-07 16:11:59 +0900998
Hugo Benichi7c342672020-09-08 09:18:14 +0900999 datapath_->StopRoutingNamespace(it->second.netns_name, it->second.host_ifname,
1000 it->second.client_subnet->BaseAddress(),
1001 it->second.client_subnet->PrefixLength(),
1002 it->second.client_subnet->AddressAtOffset(0));
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001003
1004 LOG(INFO) << "Disconnected network namespace " << it->second;
1005
1006 // This release the allocated IPv4 subnet.
1007 connected_namespaces_.erase(it);
1008}
1009
Hugo Benichi7352ad92020-04-07 16:11:59 +09001010// TODO(hugobenichi) Generalize this check to all resources created by
1011// patchpanel on behalf of a remote client.
1012void Manager::CheckConnectedNamespaces() {
1013 int max_event = 10;
1014 struct epoll_event epevents[max_event];
1015 int nready = epoll_wait(connected_namespaces_epollfd_, epevents, max_event,
1016 0 /* do not block */);
1017 if (nready < 0)
1018 PLOG(ERROR) << "CheckConnectedNamespaces: epoll_wait(0) failed";
1019
1020 for (int i = 0; i < nready; i++)
1021 if (epevents[i].events & (EPOLLHUP | EPOLLERR))
1022 DisconnectNamespace(epevents[i].data.fd);
1023
1024 if (connected_namespaces_.empty()) {
1025 LOG(INFO) << "Stopping ConnectNamespace client fds monitoring";
1026 return;
1027 }
1028
Qijiang Fan2d7aeb42020-05-19 02:06:39 +09001029 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Hugo Benichi7352ad92020-04-07 16:11:59 +09001030 FROM_HERE,
1031 base::Bind(&Manager::CheckConnectedNamespaces,
Hugo Benichie8758b52020-04-03 14:49:01 +09001032 weak_factory_.GetWeakPtr()),
Hugo Benichi7352ad92020-04-07 16:11:59 +09001033 kConnectNamespaceCheckInterval);
1034}
1035
Jason Jeremy Imanc28df852020-07-11 17:38:26 +09001036bool Manager::ModifyPortRule(const patchpanel::ModifyPortRuleRequest& request) {
1037 switch (request.proto()) {
1038 case patchpanel::ModifyPortRuleRequest::TCP:
1039 case patchpanel::ModifyPortRuleRequest::UDP:
1040 break;
1041 default:
1042 LOG(ERROR) << "Unknown protocol " << request.proto();
1043 return false;
1044 }
1045
1046 switch (request.op()) {
1047 case patchpanel::ModifyPortRuleRequest::CREATE:
1048 switch (request.type()) {
1049 case patchpanel::ModifyPortRuleRequest::ACCESS:
1050 return firewall_.AddAcceptRules(request.proto(),
1051 request.input_dst_port(),
1052 request.input_ifname());
1053 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
1054 return firewall_.AddLoopbackLockdownRules(request.proto(),
1055 request.input_dst_port());
1056 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1057 return firewall_.AddIpv4ForwardRule(
1058 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1059 request.input_ifname(), request.dst_ip(), request.dst_port());
1060 default:
1061 LOG(ERROR) << "Unknown port rule type " << request.type();
1062 return false;
1063 }
1064 case patchpanel::ModifyPortRuleRequest::DELETE:
1065 switch (request.type()) {
1066 case patchpanel::ModifyPortRuleRequest::ACCESS:
1067 return firewall_.DeleteAcceptRules(request.proto(),
1068 request.input_dst_port(),
1069 request.input_ifname());
1070 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
1071 return firewall_.DeleteLoopbackLockdownRules(
1072 request.proto(), request.input_dst_port());
1073 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1074 return firewall_.DeleteIpv4ForwardRule(
1075 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1076 request.input_ifname(), request.dst_ip(), request.dst_port());
1077 default:
1078 LOG(ERROR) << "Unknown port rule type " << request.type();
1079 return false;
1080 }
1081 default:
1082 LOG(ERROR) << "Unknown operation " << request.op();
1083 return false;
1084 }
1085}
1086
Garrick Evanse94a14e2019-11-11 10:32:13 +09001087void Manager::SendGuestMessage(const GuestMessage& msg) {
Garrick Evans96e03042019-05-28 14:30:52 +09001088 IpHelperMessage ipm;
1089 *ipm.mutable_guest_message() = msg;
Garrick Evans96e03042019-05-28 14:30:52 +09001090 adb_proxy_->SendMessage(ipm);
Garrick Evanse94a14e2019-11-11 10:32:13 +09001091 mcast_proxy_->SendMessage(ipm);
1092 nd_proxy_->SendMessage(ipm);
Garrick Evans96e03042019-05-28 14:30:52 +09001093}
1094
Garrick Evans4ac09852020-01-16 14:09:22 +09001095void Manager::StartForwarding(const std::string& ifname_physical,
1096 const std::string& ifname_virtual,
Garrick Evans4ac09852020-01-16 14:09:22 +09001097 bool ipv6,
1098 bool multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001099 if (ifname_physical.empty() || ifname_virtual.empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001100 return;
1101
1102 IpHelperMessage ipm;
1103 DeviceMessage* msg = ipm.mutable_device_message();
1104 msg->set_dev_ifname(ifname_physical);
Garrick Evans4ac09852020-01-16 14:09:22 +09001105 msg->set_br_ifname(ifname_virtual);
1106
1107 if (ipv6) {
1108 LOG(INFO) << "Starting IPv6 forwarding from " << ifname_physical << " to "
1109 << ifname_virtual;
1110
1111 if (!datapath_->AddIPv6Forwarding(ifname_physical, ifname_virtual)) {
1112 LOG(ERROR) << "Failed to setup iptables forwarding rule for IPv6 from "
1113 << ifname_physical << " to " << ifname_virtual;
1114 }
1115 if (!datapath_->MaskInterfaceFlags(ifname_physical, IFF_ALLMULTI)) {
1116 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1117 << ifname_physical;
1118 }
1119 if (!datapath_->MaskInterfaceFlags(ifname_virtual, IFF_ALLMULTI)) {
1120 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1121 << ifname_virtual;
1122 }
1123 nd_proxy_->SendMessage(ipm);
1124 }
1125
1126 if (multicast) {
1127 LOG(INFO) << "Starting multicast forwarding from " << ifname_physical
1128 << " to " << ifname_virtual;
1129 mcast_proxy_->SendMessage(ipm);
1130 }
1131}
1132
1133void Manager::StopForwarding(const std::string& ifname_physical,
1134 const std::string& ifname_virtual,
1135 bool ipv6,
1136 bool multicast) {
1137 if (ifname_physical.empty())
1138 return;
1139
1140 IpHelperMessage ipm;
1141 DeviceMessage* msg = ipm.mutable_device_message();
1142 msg->set_dev_ifname(ifname_physical);
1143 msg->set_teardown(true);
Taoyu Li7dca19a2020-03-16 16:27:07 +09001144 if (!ifname_virtual.empty()) {
1145 msg->set_br_ifname(ifname_virtual);
1146 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001147
1148 if (ipv6) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001149 if (ifname_virtual.empty()) {
1150 LOG(INFO) << "Stopping IPv6 forwarding on " << ifname_physical;
1151 } else {
1152 LOG(INFO) << "Stopping IPv6 forwarding from " << ifname_physical << " to "
1153 << ifname_virtual;
1154 datapath_->RemoveIPv6Forwarding(ifname_physical, ifname_virtual);
1155 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001156 nd_proxy_->SendMessage(ipm);
1157 }
1158
1159 if (multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001160 if (ifname_virtual.empty()) {
1161 LOG(INFO) << "Stopping multicast forwarding on " << ifname_physical;
1162 } else {
1163 LOG(INFO) << "Stopping multicast forwarding from " << ifname_physical
1164 << " to " << ifname_virtual;
1165 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001166 mcast_proxy_->SendMessage(ipm);
1167 }
1168}
1169
Taoyu Lia0727dc2020-09-24 19:54:59 +09001170void Manager::OnNDProxyMessage(const NDProxyMessage& msg) {
1171 LOG_IF(DFATAL, msg.ifname().empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001172 << "Received DeviceMessage w/ empty dev_ifname";
Taoyu Lia0727dc2020-09-24 19:54:59 +09001173 switch (msg.type()) {
1174 case NDProxyMessage::ADD_ROUTE:
1175 if (!datapath_->AddIPv6HostRoute(msg.ifname(), msg.ip6addr(), 128)) {
1176 LOG(WARNING) << "Failed to setup the IPv6 route for interface "
1177 << msg.ifname() << ", addr " << msg.ip6addr();
1178 }
1179 break;
1180 case NDProxyMessage::ADD_ADDR:
1181 if (!datapath_->AddIPv6Address(msg.ifname(), msg.ip6addr())) {
1182 LOG(WARNING) << "Failed to setup the IPv6 address for interface "
1183 << msg.ifname() << ", addr " << msg.ip6addr();
1184 }
1185 break;
1186 case NDProxyMessage::DEL_ADDR:
1187 datapath_->RemoveIPv6Address(msg.ifname(), msg.ip6addr());
1188 break;
1189 default:
1190 LOG(ERROR) << "Unknown NDProxy event " << msg.type();
1191 NOTREACHED();
Garrick Evans4ac09852020-01-16 14:09:22 +09001192 }
1193}
1194
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001195std::ostream& operator<<(std::ostream& stream,
1196 const Manager::ConnectNamespaceInfo& ns_info) {
1197 stream << "{ pid: " << ns_info.pid;
1198 if (!ns_info.outbound_ifname.empty()) {
1199 stream << ", outbound_ifname: " << ns_info.outbound_ifname;
1200 }
1201 stream << ", host_ifname: " << ns_info.host_ifname
1202 << ", client_ifname: " << ns_info.client_ifname
1203 << ", subnet: " << ns_info.client_subnet->ToCidrString() << '}';
1204 return stream;
1205}
1206
Garrick Evans3388a032020-03-24 11:25:55 +09001207} // namespace patchpanel