blob: ea55ce12a42774db16eafb49885c7a74f8a5abc1 [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();
Hugo Benichi2a940542020-10-26 18:50:49 +0900224 shill_client_->RegisterDefaultDeviceChangedHandler(base::BindRepeating(
225 &Manager::OnDefaultDeviceChanged, weak_factory_.GetWeakPtr()));
Hugo Benichibf811c62020-09-07 17:30:45 +0900226 shill_client_->RegisterDevicesChangedHandler(base::BindRepeating(
227 &Manager::OnDevicesChanged, weak_factory_.GetWeakPtr()));
228 }
Hugo Benichifda77232020-08-21 18:28:15 +0900229
Taoyu Lia0727dc2020-09-24 19:54:59 +0900230 nd_proxy_->RegisterNDProxyMessageHandler(
231 base::Bind(&Manager::OnNDProxyMessage, weak_factory_.GetWeakPtr()));
Hugo Benichifda77232020-08-21 18:28:15 +0900232
Hugo Benichifda77232020-08-21 18:28:15 +0900233 auto* const forwarder = static_cast<TrafficForwarder*>(this);
234
235 GuestMessage::GuestType arc_guest =
236 USE_ARCVM ? GuestMessage::ARC_VM : GuestMessage::ARC;
237 arc_svc_ = std::make_unique<ArcService>(shill_client_.get(), datapath_.get(),
238 &addr_mgr_, forwarder, arc_guest);
239 cros_svc_ = std::make_unique<CrostiniService>(shill_client_.get(), &addr_mgr_,
240 datapath_.get(), forwarder);
Jie Jiang84966852020-09-18 18:49:05 +0900241 network_monitor_svc_ = std::make_unique<NetworkMonitorService>(
242 shill_client_.get(),
Jie Jiang25c1b972020-11-12 15:42:53 +0900243 base::BindRepeating(&Manager::OnNeighborReachabilityEvent,
Jie Jiang84966852020-09-18 18:49:05 +0900244 weak_factory_.GetWeakPtr()));
Hugo Benichifda77232020-08-21 18:28:15 +0900245 network_monitor_svc_->Start();
246
247 counters_svc_ =
248 std::make_unique<CountersService>(shill_client_.get(), runner_.get());
249
250 nd_proxy_->Listen();
251}
252
253void Manager::OnShutdown(int* exit_code) {
254 LOG(INFO) << "Shutting down and cleaning up";
Jie Jiang84966852020-09-18 18:49:05 +0900255 network_monitor_svc_.reset();
Hugo Benichifda77232020-08-21 18:28:15 +0900256 cros_svc_.reset();
257 arc_svc_.reset();
258 close(connected_namespaces_epollfd_);
259 // Tear down any remaining connected namespace.
260 std::vector<int> connected_namespaces_fdkeys;
261 for (const auto& kv : connected_namespaces_)
262 connected_namespaces_fdkeys.push_back(kv.first);
263 for (const int fdkey : connected_namespaces_fdkeys)
264 DisconnectNamespace(fdkey);
Hugo Benichibf811c62020-09-07 17:30:45 +0900265 if (!USE_JETSTREAM_ROUTING)
266 datapath_->Stop();
Hugo Benichifda77232020-08-21 18:28:15 +0900267}
268
269void Manager::OnSubprocessExited(pid_t pid, const siginfo_t&) {
270 LOG(ERROR) << "Subprocess " << pid << " exited unexpectedly -"
271 << " attempting to restart";
272
273 HelperProcess* proc;
274 if (pid == adb_proxy_->pid()) {
275 proc = adb_proxy_.get();
276 } else if (pid == mcast_proxy_->pid()) {
277 proc = mcast_proxy_.get();
278 } else if (pid == nd_proxy_->pid()) {
279 proc = nd_proxy_.get();
280 } else {
281 LOG(DFATAL) << "Unknown child process";
282 return;
283 }
284
285 process_reaper_.ForgetChild(pid);
286
287 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
288 FROM_HERE,
289 base::Bind(&Manager::RestartSubprocess, weak_factory_.GetWeakPtr(), proc),
290 base::TimeDelta::FromMilliseconds((2 << proc->restarts()) *
291 kSubprocessRestartDelayMs));
292}
293
294void Manager::RestartSubprocess(HelperProcess* subproc) {
295 if (subproc->Restart()) {
296 DCHECK(process_reaper_.WatchForChild(
297 FROM_HERE, subproc->pid(),
298 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
299 subproc->pid())))
300 << "Failed to watch child process " << subproc->pid();
301 }
302}
303
Hugo Benichi2a940542020-10-26 18:50:49 +0900304void Manager::OnDefaultDeviceChanged(const ShillClient::Device& new_device,
305 const ShillClient::Device& prev_device) {
306 // Only take into account interface switches and ignore layer 3 property
307 // changes.
308 if (prev_device.ifname == new_device.ifname)
309 return;
310
311 if (prev_device.type == ShillClient::Device::Type::kVPN)
312 datapath_->StopVpnRouting(prev_device.ifname);
313
314 if (new_device.type == ShillClient::Device::Type::kVPN)
315 datapath_->StartVpnRouting(new_device.ifname);
316}
317
Hugo Benichi76be34a2020-08-26 22:35:54 +0900318void Manager::OnDevicesChanged(const std::set<std::string>& added,
319 const std::set<std::string>& removed) {
320 for (const std::string& ifname : removed)
321 datapath_->StopConnectionPinning(ifname);
322
323 for (const std::string& ifname : added)
324 datapath_->StartConnectionPinning(ifname);
325}
326
Garrick Evanse94a14e2019-11-11 10:32:13 +0900327bool Manager::StartArc(pid_t pid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900328 if (!arc_svc_->Start(pid))
329 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900330
331 GuestMessage msg;
332 msg.set_event(GuestMessage::START);
333 msg.set_type(GuestMessage::ARC);
334 msg.set_arc_pid(pid);
335 SendGuestMessage(msg);
336
337 return true;
338}
339
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900340void Manager::StopArc() {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900341 GuestMessage msg;
342 msg.set_event(GuestMessage::STOP);
343 msg.set_type(GuestMessage::ARC);
344 SendGuestMessage(msg);
345
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900346 // After the ARC container has stopped, the pid is not known anymore.
347 // The pid argument is ignored by ArcService.
348 arc_svc_->Stop(0);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900349}
350
Garrick Evans015b0d62020-02-07 09:06:38 +0900351bool Manager::StartArcVm(uint32_t cid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900352 if (!arc_svc_->Start(cid))
353 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900354
355 GuestMessage msg;
356 msg.set_event(GuestMessage::START);
357 msg.set_type(GuestMessage::ARC_VM);
358 msg.set_arcvm_vsock_cid(cid);
359 SendGuestMessage(msg);
360
361 return true;
362}
363
Garrick Evans015b0d62020-02-07 09:06:38 +0900364void Manager::StopArcVm(uint32_t cid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900365 GuestMessage msg;
366 msg.set_event(GuestMessage::STOP);
367 msg.set_type(GuestMessage::ARC_VM);
368 SendGuestMessage(msg);
369
Garrick Evans21173b12019-11-20 15:23:16 +0900370 arc_svc_->Stop(cid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900371}
372
Garrick Evans51d5b552020-01-30 10:42:06 +0900373bool Manager::StartCrosVm(uint64_t vm_id,
374 GuestMessage::GuestType vm_type,
Garrick Evans53a2a982020-02-05 10:53:35 +0900375 uint32_t subnet_index) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900376 DCHECK(vm_type == GuestMessage::TERMINA_VM ||
377 vm_type == GuestMessage::PLUGIN_VM);
378
379 if (!cros_svc_->Start(vm_id, vm_type == GuestMessage::TERMINA_VM,
380 subnet_index))
Garrick Evans47c19272019-11-21 10:58:21 +0900381 return false;
382
383 GuestMessage msg;
384 msg.set_event(GuestMessage::START);
Garrick Evans51d5b552020-01-30 10:42:06 +0900385 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900386 SendGuestMessage(msg);
387
388 return true;
389}
390
Garrick Evans51d5b552020-01-30 10:42:06 +0900391void Manager::StopCrosVm(uint64_t vm_id, GuestMessage::GuestType vm_type) {
Garrick Evans47c19272019-11-21 10:58:21 +0900392 GuestMessage msg;
393 msg.set_event(GuestMessage::STOP);
Garrick Evans51d5b552020-01-30 10:42:06 +0900394 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900395 SendGuestMessage(msg);
396
Garrick Evans51d5b552020-01-30 10:42:06 +0900397 cros_svc_->Stop(vm_id, vm_type == GuestMessage::TERMINA_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900398}
399
Garrick Evans08843932019-09-17 14:41:08 +0900400std::unique_ptr<dbus::Response> Manager::OnArcStartup(
401 dbus::MethodCall* method_call) {
402 LOG(INFO) << "ARC++ starting up";
403
404 std::unique_ptr<dbus::Response> dbus_response(
405 dbus::Response::FromMethodCall(method_call));
406
407 dbus::MessageReader reader(method_call);
408 dbus::MessageWriter writer(dbus_response.get());
409
410 patchpanel::ArcStartupRequest request;
411 patchpanel::ArcStartupResponse response;
412
413 if (!reader.PopArrayOfBytesAsProto(&request)) {
414 LOG(ERROR) << "Unable to parse request";
415 writer.AppendProtoAsArrayOfBytes(response);
416 return dbus_response;
417 }
418
Garrick Evanse01bf072019-11-15 09:08:19 +0900419 if (!StartArc(request.pid()))
420 LOG(ERROR) << "Failed to start ARC++ network service";
Garrick Evanse94a14e2019-11-11 10:32:13 +0900421
Garrick Evans08843932019-09-17 14:41:08 +0900422 writer.AppendProtoAsArrayOfBytes(response);
423 return dbus_response;
424}
425
426std::unique_ptr<dbus::Response> Manager::OnArcShutdown(
427 dbus::MethodCall* method_call) {
428 LOG(INFO) << "ARC++ shutting down";
429
430 std::unique_ptr<dbus::Response> dbus_response(
431 dbus::Response::FromMethodCall(method_call));
432
433 dbus::MessageReader reader(method_call);
434 dbus::MessageWriter writer(dbus_response.get());
435
436 patchpanel::ArcShutdownRequest request;
437 patchpanel::ArcShutdownResponse response;
438
439 if (!reader.PopArrayOfBytesAsProto(&request)) {
440 LOG(ERROR) << "Unable to parse request";
441 writer.AppendProtoAsArrayOfBytes(response);
442 return dbus_response;
443 }
444
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900445 StopArc();
Garrick Evanse94a14e2019-11-11 10:32:13 +0900446
Garrick Evans08843932019-09-17 14:41:08 +0900447 writer.AppendProtoAsArrayOfBytes(response);
448 return dbus_response;
449}
450
451std::unique_ptr<dbus::Response> Manager::OnArcVmStartup(
452 dbus::MethodCall* method_call) {
453 LOG(INFO) << "ARCVM starting up";
454
455 std::unique_ptr<dbus::Response> dbus_response(
456 dbus::Response::FromMethodCall(method_call));
457
458 dbus::MessageReader reader(method_call);
459 dbus::MessageWriter writer(dbus_response.get());
460
461 patchpanel::ArcVmStartupRequest request;
462 patchpanel::ArcVmStartupResponse response;
463
464 if (!reader.PopArrayOfBytesAsProto(&request)) {
465 LOG(ERROR) << "Unable to parse request";
466 writer.AppendProtoAsArrayOfBytes(response);
467 return dbus_response;
468 }
469
Garrick Evans47c19272019-11-21 10:58:21 +0900470 if (!StartArcVm(request.cid())) {
Garrick Evanse01bf072019-11-15 09:08:19 +0900471 LOG(ERROR) << "Failed to start ARCVM network service";
Garrick Evans47c19272019-11-21 10:58:21 +0900472 writer.AppendProtoAsArrayOfBytes(response);
473 return dbus_response;
Garrick Evanse01bf072019-11-15 09:08:19 +0900474 }
Garrick Evanse94a14e2019-11-11 10:32:13 +0900475
Garrick Evans47c19272019-11-21 10:58:21 +0900476 // Populate the response with the known devices.
Garrick Evans38b25a42020-04-06 15:17:42 +0900477 for (const auto* config : arc_svc_->GetDeviceConfigs()) {
478 if (config->tap_ifname().empty())
479 continue;
Garrick Evans47c19272019-11-21 10:58:21 +0900480
Garrick Evans38b25a42020-04-06 15:17:42 +0900481 auto* dev = response.add_devices();
482 dev->set_ifname(config->tap_ifname());
483 dev->set_ipv4_addr(config->guest_ipv4_addr());
Garrick Evansa0c9c972020-11-30 09:54:59 +0900484 dev->set_guest_type(NetworkDevice::ARCVM);
Garrick Evans38b25a42020-04-06 15:17:42 +0900485 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900486
Garrick Evans08843932019-09-17 14:41:08 +0900487 writer.AppendProtoAsArrayOfBytes(response);
488 return dbus_response;
489}
490
491std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
492 dbus::MethodCall* method_call) {
493 LOG(INFO) << "ARCVM shutting down";
494
495 std::unique_ptr<dbus::Response> dbus_response(
496 dbus::Response::FromMethodCall(method_call));
497
498 dbus::MessageReader reader(method_call);
499 dbus::MessageWriter writer(dbus_response.get());
500
501 patchpanel::ArcVmShutdownRequest request;
502 patchpanel::ArcVmShutdownResponse response;
503
504 if (!reader.PopArrayOfBytesAsProto(&request)) {
505 LOG(ERROR) << "Unable to parse request";
506 writer.AppendProtoAsArrayOfBytes(response);
507 return dbus_response;
508 }
509
Garrick Evans21173b12019-11-20 15:23:16 +0900510 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900511
Garrick Evans08843932019-09-17 14:41:08 +0900512 writer.AppendProtoAsArrayOfBytes(response);
513 return dbus_response;
514}
515
Garrick Evans47c19272019-11-21 10:58:21 +0900516std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
517 dbus::MethodCall* method_call) {
518 LOG(INFO) << "Termina VM starting up";
519
520 std::unique_ptr<dbus::Response> dbus_response(
521 dbus::Response::FromMethodCall(method_call));
522
523 dbus::MessageReader reader(method_call);
524 dbus::MessageWriter writer(dbus_response.get());
525
526 patchpanel::TerminaVmStartupRequest request;
527 patchpanel::TerminaVmStartupResponse response;
528
529 if (!reader.PopArrayOfBytesAsProto(&request)) {
530 LOG(ERROR) << "Unable to parse request";
531 writer.AppendProtoAsArrayOfBytes(response);
532 return dbus_response;
533 }
534
535 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900536 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900537 LOG(ERROR) << "Failed to start Termina VM network service";
538 writer.AppendProtoAsArrayOfBytes(response);
539 return dbus_response;
540 }
541
Garrick Evans51d5b552020-01-30 10:42:06 +0900542 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900543 if (!tap) {
544 LOG(DFATAL) << "TAP device missing";
545 writer.AppendProtoAsArrayOfBytes(response);
546 return dbus_response;
547 }
Garrick Evans47c19272019-11-21 10:58:21 +0900548
Garrick Evansb1c93712020-01-22 09:28:25 +0900549 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900550 dev->set_ifname(tap->host_ifname());
Garrick Evansa0c9c972020-11-30 09:54:59 +0900551 dev->set_guest_type(NetworkDevice::TERMINA_VM);
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900552 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900553 if (!subnet) {
554 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
555 writer.AppendProtoAsArrayOfBytes(response);
556 return dbus_response;
557 }
558 auto* resp_subnet = dev->mutable_ipv4_subnet();
559 resp_subnet->set_base_addr(subnet->BaseAddress());
560 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900561 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900562 if (!subnet) {
563 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
564 writer.AppendProtoAsArrayOfBytes(response);
565 return dbus_response;
566 }
567 resp_subnet = response.mutable_container_subnet();
568 resp_subnet->set_base_addr(subnet->BaseAddress());
569 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900570
571 writer.AppendProtoAsArrayOfBytes(response);
572 return dbus_response;
573}
574
575std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
576 dbus::MethodCall* method_call) {
577 LOG(INFO) << "Termina VM shutting down";
578
579 std::unique_ptr<dbus::Response> dbus_response(
580 dbus::Response::FromMethodCall(method_call));
581
582 dbus::MessageReader reader(method_call);
583 dbus::MessageWriter writer(dbus_response.get());
584
585 patchpanel::TerminaVmShutdownRequest request;
586 patchpanel::TerminaVmShutdownResponse response;
587
588 if (!reader.PopArrayOfBytesAsProto(&request)) {
589 LOG(ERROR) << "Unable to parse request";
590 writer.AppendProtoAsArrayOfBytes(response);
591 return dbus_response;
592 }
593
Garrick Evans51d5b552020-01-30 10:42:06 +0900594 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
595
596 writer.AppendProtoAsArrayOfBytes(response);
597 return dbus_response;
598}
599
600std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
601 dbus::MethodCall* method_call) {
602 LOG(INFO) << "Plugin VM starting up";
603
604 std::unique_ptr<dbus::Response> dbus_response(
605 dbus::Response::FromMethodCall(method_call));
606
607 dbus::MessageReader reader(method_call);
608 dbus::MessageWriter writer(dbus_response.get());
609
610 patchpanel::PluginVmStartupRequest request;
611 patchpanel::PluginVmStartupResponse response;
612
613 if (!reader.PopArrayOfBytesAsProto(&request)) {
614 LOG(ERROR) << "Unable to parse request";
615 writer.AppendProtoAsArrayOfBytes(response);
616 return dbus_response;
617 }
618
Garrick Evans08fb34b2020-02-20 10:50:17 +0900619 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900620 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900621 LOG(ERROR) << "Failed to start Plugin VM network service";
622 writer.AppendProtoAsArrayOfBytes(response);
623 return dbus_response;
624 }
625
626 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
627 if (!tap) {
628 LOG(DFATAL) << "TAP device missing";
629 writer.AppendProtoAsArrayOfBytes(response);
630 return dbus_response;
631 }
632
Garrick Evans51d5b552020-01-30 10:42:06 +0900633 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900634 dev->set_ifname(tap->host_ifname());
Garrick Evansa0c9c972020-11-30 09:54:59 +0900635 dev->set_guest_type(NetworkDevice::PLUGIN_VM);
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900636 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900637 if (!subnet) {
638 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
639 writer.AppendProtoAsArrayOfBytes(response);
640 return dbus_response;
641 }
642 auto* resp_subnet = dev->mutable_ipv4_subnet();
643 resp_subnet->set_base_addr(subnet->BaseAddress());
644 resp_subnet->set_prefix_len(subnet->PrefixLength());
645
646 writer.AppendProtoAsArrayOfBytes(response);
647 return dbus_response;
648}
649
650std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
651 dbus::MethodCall* method_call) {
652 LOG(INFO) << "Plugin VM shutting down";
653
654 std::unique_ptr<dbus::Response> dbus_response(
655 dbus::Response::FromMethodCall(method_call));
656
657 dbus::MessageReader reader(method_call);
658 dbus::MessageWriter writer(dbus_response.get());
659
660 patchpanel::PluginVmShutdownRequest request;
661 patchpanel::PluginVmShutdownResponse response;
662
663 if (!reader.PopArrayOfBytesAsProto(&request)) {
664 LOG(ERROR) << "Unable to parse request";
665 writer.AppendProtoAsArrayOfBytes(response);
666 return dbus_response;
667 }
668
669 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900670
671 writer.AppendProtoAsArrayOfBytes(response);
672 return dbus_response;
673}
674
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900675std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
676 dbus::MethodCall* method_call) {
677 std::unique_ptr<dbus::Response> dbus_response(
678 dbus::Response::FromMethodCall(method_call));
679
680 dbus::MessageReader reader(method_call);
681 dbus::MessageWriter writer(dbus_response.get());
682
683 patchpanel::SetVpnIntentRequest request;
684 patchpanel::SetVpnIntentResponse response;
685
686 bool success = reader.PopArrayOfBytesAsProto(&request);
687 if (!success) {
688 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
689 // Do not return yet to make sure we close the received fd.
690 }
691
692 base::ScopedFD client_socket;
693 reader.PopFileDescriptor(&client_socket);
694
695 if (success)
696 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
697
698 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900699
700 writer.AppendProtoAsArrayOfBytes(response);
701 return dbus_response;
702}
703
704std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
705 dbus::MethodCall* method_call) {
706 std::unique_ptr<dbus::Response> dbus_response(
707 dbus::Response::FromMethodCall(method_call));
708
709 dbus::MessageReader reader(method_call);
710 dbus::MessageWriter writer(dbus_response.get());
711
712 patchpanel::ConnectNamespaceRequest request;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900713
714 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900715 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
716 // Do not return yet to make sure we close the received fd and
717 // validate other arguments.
Hugo Benichi7c342672020-09-08 09:18:14 +0900718 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
719 return dbus_response;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900720 }
721
Hugo Benichicc6850f2020-01-17 13:26:06 +0900722 base::ScopedFD client_fd;
723 reader.PopFileDescriptor(&client_fd);
724 if (!client_fd.is_valid()) {
725 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
Hugo Benichi7c342672020-09-08 09:18:14 +0900726 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
727 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900728 }
729
730 pid_t pid = request.pid();
731 {
732 ScopedNS ns(pid);
733 if (!ns.IsValid()) {
734 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900735 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
736 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900737 }
738 }
739
740 const std::string& outbound_ifname = request.outbound_physical_device();
741 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
742 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
743 << outbound_ifname;
Hugo Benichi7c342672020-09-08 09:18:14 +0900744 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
745 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900746 }
747
Hugo Benichi7c342672020-09-08 09:18:14 +0900748 auto response = ConnectNamespace(std::move(client_fd), request);
749 writer.AppendProtoAsArrayOfBytes(*response);
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900750 return dbus_response;
751}
752
Jie Jiang493cde42020-07-17 21:43:39 +0900753std::unique_ptr<dbus::Response> Manager::OnGetTrafficCounters(
754 dbus::MethodCall* method_call) {
755 std::unique_ptr<dbus::Response> dbus_response(
756 dbus::Response::FromMethodCall(method_call));
757
758 dbus::MessageReader reader(method_call);
759 dbus::MessageWriter writer(dbus_response.get());
760
761 patchpanel::TrafficCountersRequest request;
762 patchpanel::TrafficCountersResponse response;
763
764 if (!reader.PopArrayOfBytesAsProto(&request)) {
765 LOG(ERROR) << "Unable to parse TrafficCountersRequest";
766 writer.AppendProtoAsArrayOfBytes(response);
767 return dbus_response;
768 }
769
770 const std::set<std::string> devices{request.devices().begin(),
771 request.devices().end()};
772 const auto counters = counters_svc_->GetCounters(devices);
773 for (const auto& kv : counters) {
774 auto* traffic_counter = response.add_counters();
775 const auto& source_and_device = kv.first;
776 const auto& counter = kv.second;
777 traffic_counter->set_source(source_and_device.first);
778 traffic_counter->set_device(source_and_device.second);
779 traffic_counter->set_rx_bytes(counter.rx_bytes);
780 traffic_counter->set_rx_packets(counter.rx_packets);
781 traffic_counter->set_tx_bytes(counter.tx_bytes);
782 traffic_counter->set_tx_packets(counter.tx_packets);
783 }
784
785 writer.AppendProtoAsArrayOfBytes(response);
786 return dbus_response;
787}
788
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900789std::unique_ptr<dbus::Response> Manager::OnModifyPortRule(
790 dbus::MethodCall* method_call) {
791 std::unique_ptr<dbus::Response> dbus_response(
792 dbus::Response::FromMethodCall(method_call));
793
794 dbus::MessageReader reader(method_call);
795 dbus::MessageWriter writer(dbus_response.get());
796
797 patchpanel::ModifyPortRuleRequest request;
798 patchpanel::ModifyPortRuleResponse response;
799
800 if (!reader.PopArrayOfBytesAsProto(&request)) {
801 LOG(ERROR) << "Unable to parse ModifyPortRequest";
802 writer.AppendProtoAsArrayOfBytes(response);
803 return dbus_response;
804 }
805
Jason Jeremy Imanc28df852020-07-11 17:38:26 +0900806 response.set_success(ModifyPortRule(request));
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900807 writer.AppendProtoAsArrayOfBytes(response);
808 return dbus_response;
809}
810
Jie Jiang25c1b972020-11-12 15:42:53 +0900811void Manager::OnNeighborReachabilityEvent(
Jie Jiang84966852020-09-18 18:49:05 +0900812 int ifindex,
813 const shill::IPAddress& ip_addr,
814 NeighborLinkMonitor::NeighborRole role,
Jie Jiang25c1b972020-11-12 15:42:53 +0900815 NeighborReachabilityEventSignal::EventType event_type) {
Jie Jiang84966852020-09-18 18:49:05 +0900816 if (!ip_addr.IsValid()) {
817 LOG(DFATAL) << "ip_addr is not valid";
818 return;
819 }
820
Jie Jiang25c1b972020-11-12 15:42:53 +0900821 using SignalProto = NeighborReachabilityEventSignal;
Jie Jiang84966852020-09-18 18:49:05 +0900822 SignalProto proto;
823 proto.set_ifindex(ifindex);
824 proto.set_ip_addr(ip_addr.ToString());
Jie Jiang25c1b972020-11-12 15:42:53 +0900825 proto.set_type(event_type);
Jie Jiang84966852020-09-18 18:49:05 +0900826 switch (role) {
827 case NeighborLinkMonitor::NeighborRole::kGateway:
828 proto.set_role(SignalProto::GATEWAY);
829 break;
830 case NeighborLinkMonitor::NeighborRole::kDNSServer:
831 proto.set_role(SignalProto::DNS_SERVER);
832 break;
833 case NeighborLinkMonitor::NeighborRole::kGatewayAndDNSServer:
834 proto.set_role(SignalProto::GATEWAY_AND_DNS_SERVER);
835 break;
836 default:
837 NOTREACHED();
838 }
839
Jie Jiang25c1b972020-11-12 15:42:53 +0900840 dbus::Signal signal(kPatchPanelInterface, kNeighborReachabilityEventSignal);
Jie Jiang84966852020-09-18 18:49:05 +0900841 dbus::MessageWriter writer(&signal);
842 if (!writer.AppendProtoAsArrayOfBytes(proto)) {
Jie Jiang25c1b972020-11-12 15:42:53 +0900843 LOG(ERROR) << "Failed to encode proto NeighborReachabilityEventSignal";
Jie Jiang84966852020-09-18 18:49:05 +0900844 return;
845 }
846
847 dbus_svc_path_->SendSignal(&signal);
848}
849
Hugo Benichi7c342672020-09-08 09:18:14 +0900850std::unique_ptr<patchpanel::ConnectNamespaceResponse> Manager::ConnectNamespace(
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900851 base::ScopedFD client_fd,
Hugo Benichi7c342672020-09-08 09:18:14 +0900852 const patchpanel::ConnectNamespaceRequest& request) {
853 auto response = std::make_unique<patchpanel::ConnectNamespaceResponse>();
854
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900855 std::unique_ptr<Subnet> subnet =
856 addr_mgr_.AllocateIPv4Subnet(AddressManager::Guest::MINIJAIL_NETNS);
857 if (!subnet) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900858 LOG(ERROR) << "ConnectNamespace: exhausted IPv4 subnet space";
859 return response;
Hugo Benichie8758b52020-04-03 14:49:01 +0900860 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900861
Hugo Benichi7352ad92020-04-07 16:11:59 +0900862 // Dup the client fd into our own: this guarantees that the fd number will
863 // be stable and tied to the actual kernel resources used by the client.
864 base::ScopedFD local_client_fd(dup(client_fd.get()));
865 if (!local_client_fd.is_valid()) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900866 PLOG(ERROR) << "ConnectNamespace: failed to dup() client fd";
867 return response;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900868 }
869
Hugo Benichi7c342672020-09-08 09:18:14 +0900870 // Add the duped fd to the epoll watcher.
Hugo Benichi7352ad92020-04-07 16:11:59 +0900871 // TODO(hugobenichi) Find a way to reuse base::FileDescriptorWatcher for
872 // listening to EPOLLHUP.
873 struct epoll_event epevent;
874 epevent.events = EPOLLIN; // EPOLLERR | EPOLLHUP are always waited for.
875 epevent.data.fd = local_client_fd.get();
876 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_ADD,
877 local_client_fd.get(), &epevent) != 0) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900878 PLOG(ERROR) << "ConnectNamespace: epoll_ctl(EPOLL_CTL_ADD) failed";
879 return response;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900880 }
881
Hugo Benichi7c342672020-09-08 09:18:14 +0900882 const std::string ifname_id = std::to_string(connected_namespaces_next_id_);
883 const std::string netns_name = "connected_netns_" + ifname_id;
884 const std::string host_ifname = "arc_ns" + ifname_id;
885 const std::string client_ifname = "veth" + ifname_id;
886 if (!datapath_->StartRoutingNamespace(
887 request.pid(), netns_name, host_ifname, client_ifname,
888 subnet->BaseAddress(), subnet->PrefixLength(),
889 subnet->AddressAtOffset(0), subnet->AddressAtOffset(1),
890 addr_mgr_.GenerateMacAddress())) {
891 LOG(ERROR) << "ConnectNamespace: failed to setup datapath";
892 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL,
893 local_client_fd.get(), nullptr) != 0)
894 PLOG(ERROR) << "ConnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
895 return response;
896 }
897
898 // TODO(hugobenichi) The peer and host addresses are swapped in the response
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900899 // Prepare the response before storing ConnectNamespaceInfo.
Hugo Benichi7c342672020-09-08 09:18:14 +0900900 response->set_peer_ifname(client_ifname);
901 response->set_peer_ipv4_address(subnet->AddressAtOffset(0));
902 response->set_host_ifname(host_ifname);
903 response->set_host_ipv4_address(subnet->AddressAtOffset(1));
904 auto* response_subnet = response->mutable_ipv4_subnet();
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900905 response_subnet->set_base_addr(subnet->BaseAddress());
906 response_subnet->set_prefix_len(subnet->PrefixLength());
907
908 // Store ConnectNamespaceInfo
909 connected_namespaces_next_id_++;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900910 int fdkey = local_client_fd.release();
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900911 connected_namespaces_[fdkey] = {};
912 ConnectNamespaceInfo& ns_info = connected_namespaces_[fdkey];
913 ns_info.pid = request.pid();
Hugo Benichi33860d72020-07-09 16:34:01 +0900914 ns_info.netns_name = std::move(netns_name);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900915 ns_info.outbound_ifname = request.outbound_physical_device();
916 ns_info.host_ifname = std::move(host_ifname);
917 ns_info.client_ifname = std::move(client_ifname);
918 ns_info.client_subnet = std::move(subnet);
919
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900920 LOG(INFO) << "Connected network namespace " << ns_info;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900921
922 if (connected_namespaces_.size() == 1) {
923 LOG(INFO) << "Starting ConnectNamespace client fds monitoring";
924 CheckConnectedNamespaces();
925 }
Hugo Benichi7c342672020-09-08 09:18:14 +0900926
927 return response;
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900928}
929
930void Manager::DisconnectNamespace(int client_fd) {
931 auto it = connected_namespaces_.find(client_fd);
932 if (it == connected_namespaces_.end()) {
933 LOG(ERROR) << "No ConnectNamespaceInfo found for client_fd " << client_fd;
934 return;
935 }
936
Hugo Benichi7352ad92020-04-07 16:11:59 +0900937 // Remove the client fd dupe from the epoll watcher and close it.
938 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL, client_fd,
Hugo Benichie8758b52020-04-03 14:49:01 +0900939 nullptr) != 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900940 PLOG(ERROR) << "DisconnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900941 if (close(client_fd) < 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900942 PLOG(ERROR) << "DisconnectNamespace: close(client_fd) failed";
Hugo Benichi7352ad92020-04-07 16:11:59 +0900943
Hugo Benichi7c342672020-09-08 09:18:14 +0900944 datapath_->StopRoutingNamespace(it->second.netns_name, it->second.host_ifname,
945 it->second.client_subnet->BaseAddress(),
946 it->second.client_subnet->PrefixLength(),
947 it->second.client_subnet->AddressAtOffset(0));
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900948
949 LOG(INFO) << "Disconnected network namespace " << it->second;
950
951 // This release the allocated IPv4 subnet.
952 connected_namespaces_.erase(it);
953}
954
Hugo Benichi7352ad92020-04-07 16:11:59 +0900955// TODO(hugobenichi) Generalize this check to all resources created by
956// patchpanel on behalf of a remote client.
957void Manager::CheckConnectedNamespaces() {
958 int max_event = 10;
959 struct epoll_event epevents[max_event];
960 int nready = epoll_wait(connected_namespaces_epollfd_, epevents, max_event,
961 0 /* do not block */);
962 if (nready < 0)
963 PLOG(ERROR) << "CheckConnectedNamespaces: epoll_wait(0) failed";
964
965 for (int i = 0; i < nready; i++)
966 if (epevents[i].events & (EPOLLHUP | EPOLLERR))
967 DisconnectNamespace(epevents[i].data.fd);
968
969 if (connected_namespaces_.empty()) {
970 LOG(INFO) << "Stopping ConnectNamespace client fds monitoring";
971 return;
972 }
973
Qijiang Fan2d7aeb42020-05-19 02:06:39 +0900974 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Hugo Benichi7352ad92020-04-07 16:11:59 +0900975 FROM_HERE,
976 base::Bind(&Manager::CheckConnectedNamespaces,
Hugo Benichie8758b52020-04-03 14:49:01 +0900977 weak_factory_.GetWeakPtr()),
Hugo Benichi7352ad92020-04-07 16:11:59 +0900978 kConnectNamespaceCheckInterval);
979}
980
Jason Jeremy Imanc28df852020-07-11 17:38:26 +0900981bool Manager::ModifyPortRule(const patchpanel::ModifyPortRuleRequest& request) {
982 switch (request.proto()) {
983 case patchpanel::ModifyPortRuleRequest::TCP:
984 case patchpanel::ModifyPortRuleRequest::UDP:
985 break;
986 default:
987 LOG(ERROR) << "Unknown protocol " << request.proto();
988 return false;
989 }
990
991 switch (request.op()) {
992 case patchpanel::ModifyPortRuleRequest::CREATE:
993 switch (request.type()) {
994 case patchpanel::ModifyPortRuleRequest::ACCESS:
995 return firewall_.AddAcceptRules(request.proto(),
996 request.input_dst_port(),
997 request.input_ifname());
998 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
999 return firewall_.AddLoopbackLockdownRules(request.proto(),
1000 request.input_dst_port());
1001 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1002 return firewall_.AddIpv4ForwardRule(
1003 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1004 request.input_ifname(), request.dst_ip(), request.dst_port());
1005 default:
1006 LOG(ERROR) << "Unknown port rule type " << request.type();
1007 return false;
1008 }
1009 case patchpanel::ModifyPortRuleRequest::DELETE:
1010 switch (request.type()) {
1011 case patchpanel::ModifyPortRuleRequest::ACCESS:
1012 return firewall_.DeleteAcceptRules(request.proto(),
1013 request.input_dst_port(),
1014 request.input_ifname());
1015 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
1016 return firewall_.DeleteLoopbackLockdownRules(
1017 request.proto(), request.input_dst_port());
1018 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1019 return firewall_.DeleteIpv4ForwardRule(
1020 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1021 request.input_ifname(), request.dst_ip(), request.dst_port());
1022 default:
1023 LOG(ERROR) << "Unknown port rule type " << request.type();
1024 return false;
1025 }
1026 default:
1027 LOG(ERROR) << "Unknown operation " << request.op();
1028 return false;
1029 }
1030}
1031
Garrick Evanse94a14e2019-11-11 10:32:13 +09001032void Manager::SendGuestMessage(const GuestMessage& msg) {
Garrick Evans96e03042019-05-28 14:30:52 +09001033 IpHelperMessage ipm;
1034 *ipm.mutable_guest_message() = msg;
Garrick Evans96e03042019-05-28 14:30:52 +09001035 adb_proxy_->SendMessage(ipm);
Garrick Evanse94a14e2019-11-11 10:32:13 +09001036 mcast_proxy_->SendMessage(ipm);
1037 nd_proxy_->SendMessage(ipm);
Garrick Evans96e03042019-05-28 14:30:52 +09001038}
1039
Garrick Evans4ac09852020-01-16 14:09:22 +09001040void Manager::StartForwarding(const std::string& ifname_physical,
1041 const std::string& ifname_virtual,
Garrick Evans4ac09852020-01-16 14:09:22 +09001042 bool ipv6,
1043 bool multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001044 if (ifname_physical.empty() || ifname_virtual.empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001045 return;
1046
1047 IpHelperMessage ipm;
1048 DeviceMessage* msg = ipm.mutable_device_message();
1049 msg->set_dev_ifname(ifname_physical);
Garrick Evans4ac09852020-01-16 14:09:22 +09001050 msg->set_br_ifname(ifname_virtual);
1051
1052 if (ipv6) {
1053 LOG(INFO) << "Starting IPv6 forwarding from " << ifname_physical << " to "
1054 << ifname_virtual;
1055
1056 if (!datapath_->AddIPv6Forwarding(ifname_physical, ifname_virtual)) {
1057 LOG(ERROR) << "Failed to setup iptables forwarding rule for IPv6 from "
1058 << ifname_physical << " to " << ifname_virtual;
1059 }
1060 if (!datapath_->MaskInterfaceFlags(ifname_physical, IFF_ALLMULTI)) {
1061 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1062 << ifname_physical;
1063 }
1064 if (!datapath_->MaskInterfaceFlags(ifname_virtual, IFF_ALLMULTI)) {
1065 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1066 << ifname_virtual;
1067 }
1068 nd_proxy_->SendMessage(ipm);
1069 }
1070
1071 if (multicast) {
1072 LOG(INFO) << "Starting multicast forwarding from " << ifname_physical
1073 << " to " << ifname_virtual;
1074 mcast_proxy_->SendMessage(ipm);
1075 }
1076}
1077
1078void Manager::StopForwarding(const std::string& ifname_physical,
1079 const std::string& ifname_virtual,
1080 bool ipv6,
1081 bool multicast) {
1082 if (ifname_physical.empty())
1083 return;
1084
1085 IpHelperMessage ipm;
1086 DeviceMessage* msg = ipm.mutable_device_message();
1087 msg->set_dev_ifname(ifname_physical);
1088 msg->set_teardown(true);
Taoyu Li7dca19a2020-03-16 16:27:07 +09001089 if (!ifname_virtual.empty()) {
1090 msg->set_br_ifname(ifname_virtual);
1091 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001092
1093 if (ipv6) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001094 if (ifname_virtual.empty()) {
1095 LOG(INFO) << "Stopping IPv6 forwarding on " << ifname_physical;
1096 } else {
1097 LOG(INFO) << "Stopping IPv6 forwarding from " << ifname_physical << " to "
1098 << ifname_virtual;
1099 datapath_->RemoveIPv6Forwarding(ifname_physical, ifname_virtual);
1100 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001101 nd_proxy_->SendMessage(ipm);
1102 }
1103
1104 if (multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001105 if (ifname_virtual.empty()) {
1106 LOG(INFO) << "Stopping multicast forwarding on " << ifname_physical;
1107 } else {
1108 LOG(INFO) << "Stopping multicast forwarding from " << ifname_physical
1109 << " to " << ifname_virtual;
1110 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001111 mcast_proxy_->SendMessage(ipm);
1112 }
1113}
1114
Taoyu Lia0727dc2020-09-24 19:54:59 +09001115void Manager::OnNDProxyMessage(const NDProxyMessage& msg) {
1116 LOG_IF(DFATAL, msg.ifname().empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001117 << "Received DeviceMessage w/ empty dev_ifname";
Taoyu Lia0727dc2020-09-24 19:54:59 +09001118 switch (msg.type()) {
1119 case NDProxyMessage::ADD_ROUTE:
1120 if (!datapath_->AddIPv6HostRoute(msg.ifname(), msg.ip6addr(), 128)) {
1121 LOG(WARNING) << "Failed to setup the IPv6 route for interface "
1122 << msg.ifname() << ", addr " << msg.ip6addr();
1123 }
1124 break;
1125 case NDProxyMessage::ADD_ADDR:
1126 if (!datapath_->AddIPv6Address(msg.ifname(), msg.ip6addr())) {
1127 LOG(WARNING) << "Failed to setup the IPv6 address for interface "
1128 << msg.ifname() << ", addr " << msg.ip6addr();
1129 }
1130 break;
1131 case NDProxyMessage::DEL_ADDR:
1132 datapath_->RemoveIPv6Address(msg.ifname(), msg.ip6addr());
1133 break;
1134 default:
1135 LOG(ERROR) << "Unknown NDProxy event " << msg.type();
1136 NOTREACHED();
Garrick Evans4ac09852020-01-16 14:09:22 +09001137 }
1138}
1139
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001140std::ostream& operator<<(std::ostream& stream,
1141 const Manager::ConnectNamespaceInfo& ns_info) {
1142 stream << "{ pid: " << ns_info.pid;
1143 if (!ns_info.outbound_ifname.empty()) {
1144 stream << ", outbound_ifname: " << ns_info.outbound_ifname;
1145 }
1146 stream << ", host_ifname: " << ns_info.host_ifname
1147 << ", client_ifname: " << ns_info.client_ifname
1148 << ", subnet: " << ns_info.client_subnet->ToCidrString() << '}';
1149 return stream;
1150}
1151
Garrick Evans3388a032020-03-24 11:25:55 +09001152} // namespace patchpanel