blob: 2872e15cbfb4c7c420920f709fddbc8ed8a6590d [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());
484 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900485
Garrick Evans08843932019-09-17 14:41:08 +0900486 writer.AppendProtoAsArrayOfBytes(response);
487 return dbus_response;
488}
489
490std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
491 dbus::MethodCall* method_call) {
492 LOG(INFO) << "ARCVM shutting down";
493
494 std::unique_ptr<dbus::Response> dbus_response(
495 dbus::Response::FromMethodCall(method_call));
496
497 dbus::MessageReader reader(method_call);
498 dbus::MessageWriter writer(dbus_response.get());
499
500 patchpanel::ArcVmShutdownRequest request;
501 patchpanel::ArcVmShutdownResponse response;
502
503 if (!reader.PopArrayOfBytesAsProto(&request)) {
504 LOG(ERROR) << "Unable to parse request";
505 writer.AppendProtoAsArrayOfBytes(response);
506 return dbus_response;
507 }
508
Garrick Evans21173b12019-11-20 15:23:16 +0900509 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900510
Garrick Evans08843932019-09-17 14:41:08 +0900511 writer.AppendProtoAsArrayOfBytes(response);
512 return dbus_response;
513}
514
Garrick Evans47c19272019-11-21 10:58:21 +0900515std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
516 dbus::MethodCall* method_call) {
517 LOG(INFO) << "Termina VM starting up";
518
519 std::unique_ptr<dbus::Response> dbus_response(
520 dbus::Response::FromMethodCall(method_call));
521
522 dbus::MessageReader reader(method_call);
523 dbus::MessageWriter writer(dbus_response.get());
524
525 patchpanel::TerminaVmStartupRequest request;
526 patchpanel::TerminaVmStartupResponse response;
527
528 if (!reader.PopArrayOfBytesAsProto(&request)) {
529 LOG(ERROR) << "Unable to parse request";
530 writer.AppendProtoAsArrayOfBytes(response);
531 return dbus_response;
532 }
533
534 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900535 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900536 LOG(ERROR) << "Failed to start Termina VM network service";
537 writer.AppendProtoAsArrayOfBytes(response);
538 return dbus_response;
539 }
540
Garrick Evans51d5b552020-01-30 10:42:06 +0900541 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900542 if (!tap) {
543 LOG(DFATAL) << "TAP device missing";
544 writer.AppendProtoAsArrayOfBytes(response);
545 return dbus_response;
546 }
Garrick Evans47c19272019-11-21 10:58:21 +0900547
Garrick Evansb1c93712020-01-22 09:28:25 +0900548 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900549 dev->set_ifname(tap->host_ifname());
550 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900551 if (!subnet) {
552 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
553 writer.AppendProtoAsArrayOfBytes(response);
554 return dbus_response;
555 }
556 auto* resp_subnet = dev->mutable_ipv4_subnet();
557 resp_subnet->set_base_addr(subnet->BaseAddress());
558 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900559 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900560 if (!subnet) {
561 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
562 writer.AppendProtoAsArrayOfBytes(response);
563 return dbus_response;
564 }
565 resp_subnet = response.mutable_container_subnet();
566 resp_subnet->set_base_addr(subnet->BaseAddress());
567 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900568
569 writer.AppendProtoAsArrayOfBytes(response);
570 return dbus_response;
571}
572
573std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
574 dbus::MethodCall* method_call) {
575 LOG(INFO) << "Termina VM shutting down";
576
577 std::unique_ptr<dbus::Response> dbus_response(
578 dbus::Response::FromMethodCall(method_call));
579
580 dbus::MessageReader reader(method_call);
581 dbus::MessageWriter writer(dbus_response.get());
582
583 patchpanel::TerminaVmShutdownRequest request;
584 patchpanel::TerminaVmShutdownResponse response;
585
586 if (!reader.PopArrayOfBytesAsProto(&request)) {
587 LOG(ERROR) << "Unable to parse request";
588 writer.AppendProtoAsArrayOfBytes(response);
589 return dbus_response;
590 }
591
Garrick Evans51d5b552020-01-30 10:42:06 +0900592 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
593
594 writer.AppendProtoAsArrayOfBytes(response);
595 return dbus_response;
596}
597
598std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
599 dbus::MethodCall* method_call) {
600 LOG(INFO) << "Plugin VM starting up";
601
602 std::unique_ptr<dbus::Response> dbus_response(
603 dbus::Response::FromMethodCall(method_call));
604
605 dbus::MessageReader reader(method_call);
606 dbus::MessageWriter writer(dbus_response.get());
607
608 patchpanel::PluginVmStartupRequest request;
609 patchpanel::PluginVmStartupResponse response;
610
611 if (!reader.PopArrayOfBytesAsProto(&request)) {
612 LOG(ERROR) << "Unable to parse request";
613 writer.AppendProtoAsArrayOfBytes(response);
614 return dbus_response;
615 }
616
Garrick Evans08fb34b2020-02-20 10:50:17 +0900617 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900618 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900619 LOG(ERROR) << "Failed to start Plugin VM network service";
620 writer.AppendProtoAsArrayOfBytes(response);
621 return dbus_response;
622 }
623
624 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
625 if (!tap) {
626 LOG(DFATAL) << "TAP device missing";
627 writer.AppendProtoAsArrayOfBytes(response);
628 return dbus_response;
629 }
630
Garrick Evans51d5b552020-01-30 10:42:06 +0900631 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900632 dev->set_ifname(tap->host_ifname());
633 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900634 if (!subnet) {
635 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
636 writer.AppendProtoAsArrayOfBytes(response);
637 return dbus_response;
638 }
639 auto* resp_subnet = dev->mutable_ipv4_subnet();
640 resp_subnet->set_base_addr(subnet->BaseAddress());
641 resp_subnet->set_prefix_len(subnet->PrefixLength());
642
643 writer.AppendProtoAsArrayOfBytes(response);
644 return dbus_response;
645}
646
647std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
648 dbus::MethodCall* method_call) {
649 LOG(INFO) << "Plugin VM shutting down";
650
651 std::unique_ptr<dbus::Response> dbus_response(
652 dbus::Response::FromMethodCall(method_call));
653
654 dbus::MessageReader reader(method_call);
655 dbus::MessageWriter writer(dbus_response.get());
656
657 patchpanel::PluginVmShutdownRequest request;
658 patchpanel::PluginVmShutdownResponse response;
659
660 if (!reader.PopArrayOfBytesAsProto(&request)) {
661 LOG(ERROR) << "Unable to parse request";
662 writer.AppendProtoAsArrayOfBytes(response);
663 return dbus_response;
664 }
665
666 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900667
668 writer.AppendProtoAsArrayOfBytes(response);
669 return dbus_response;
670}
671
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900672std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
673 dbus::MethodCall* method_call) {
674 std::unique_ptr<dbus::Response> dbus_response(
675 dbus::Response::FromMethodCall(method_call));
676
677 dbus::MessageReader reader(method_call);
678 dbus::MessageWriter writer(dbus_response.get());
679
680 patchpanel::SetVpnIntentRequest request;
681 patchpanel::SetVpnIntentResponse response;
682
683 bool success = reader.PopArrayOfBytesAsProto(&request);
684 if (!success) {
685 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
686 // Do not return yet to make sure we close the received fd.
687 }
688
689 base::ScopedFD client_socket;
690 reader.PopFileDescriptor(&client_socket);
691
692 if (success)
693 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
694
695 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900696
697 writer.AppendProtoAsArrayOfBytes(response);
698 return dbus_response;
699}
700
701std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
702 dbus::MethodCall* method_call) {
703 std::unique_ptr<dbus::Response> dbus_response(
704 dbus::Response::FromMethodCall(method_call));
705
706 dbus::MessageReader reader(method_call);
707 dbus::MessageWriter writer(dbus_response.get());
708
709 patchpanel::ConnectNamespaceRequest request;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900710
711 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900712 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
713 // Do not return yet to make sure we close the received fd and
714 // validate other arguments.
Hugo Benichi7c342672020-09-08 09:18:14 +0900715 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
716 return dbus_response;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900717 }
718
Hugo Benichicc6850f2020-01-17 13:26:06 +0900719 base::ScopedFD client_fd;
720 reader.PopFileDescriptor(&client_fd);
721 if (!client_fd.is_valid()) {
722 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
Hugo Benichi7c342672020-09-08 09:18:14 +0900723 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
724 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900725 }
726
727 pid_t pid = request.pid();
728 {
729 ScopedNS ns(pid);
730 if (!ns.IsValid()) {
731 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900732 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
733 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900734 }
735 }
736
737 const std::string& outbound_ifname = request.outbound_physical_device();
738 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
739 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
740 << outbound_ifname;
Hugo Benichi7c342672020-09-08 09:18:14 +0900741 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
742 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900743 }
744
Hugo Benichi7c342672020-09-08 09:18:14 +0900745 auto response = ConnectNamespace(std::move(client_fd), request);
746 writer.AppendProtoAsArrayOfBytes(*response);
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900747 return dbus_response;
748}
749
Jie Jiang493cde42020-07-17 21:43:39 +0900750std::unique_ptr<dbus::Response> Manager::OnGetTrafficCounters(
751 dbus::MethodCall* method_call) {
752 std::unique_ptr<dbus::Response> dbus_response(
753 dbus::Response::FromMethodCall(method_call));
754
755 dbus::MessageReader reader(method_call);
756 dbus::MessageWriter writer(dbus_response.get());
757
758 patchpanel::TrafficCountersRequest request;
759 patchpanel::TrafficCountersResponse response;
760
761 if (!reader.PopArrayOfBytesAsProto(&request)) {
762 LOG(ERROR) << "Unable to parse TrafficCountersRequest";
763 writer.AppendProtoAsArrayOfBytes(response);
764 return dbus_response;
765 }
766
767 const std::set<std::string> devices{request.devices().begin(),
768 request.devices().end()};
769 const auto counters = counters_svc_->GetCounters(devices);
770 for (const auto& kv : counters) {
771 auto* traffic_counter = response.add_counters();
772 const auto& source_and_device = kv.first;
773 const auto& counter = kv.second;
774 traffic_counter->set_source(source_and_device.first);
775 traffic_counter->set_device(source_and_device.second);
776 traffic_counter->set_rx_bytes(counter.rx_bytes);
777 traffic_counter->set_rx_packets(counter.rx_packets);
778 traffic_counter->set_tx_bytes(counter.tx_bytes);
779 traffic_counter->set_tx_packets(counter.tx_packets);
780 }
781
782 writer.AppendProtoAsArrayOfBytes(response);
783 return dbus_response;
784}
785
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900786std::unique_ptr<dbus::Response> Manager::OnModifyPortRule(
787 dbus::MethodCall* method_call) {
788 std::unique_ptr<dbus::Response> dbus_response(
789 dbus::Response::FromMethodCall(method_call));
790
791 dbus::MessageReader reader(method_call);
792 dbus::MessageWriter writer(dbus_response.get());
793
794 patchpanel::ModifyPortRuleRequest request;
795 patchpanel::ModifyPortRuleResponse response;
796
797 if (!reader.PopArrayOfBytesAsProto(&request)) {
798 LOG(ERROR) << "Unable to parse ModifyPortRequest";
799 writer.AppendProtoAsArrayOfBytes(response);
800 return dbus_response;
801 }
802
Jason Jeremy Imanc28df852020-07-11 17:38:26 +0900803 response.set_success(ModifyPortRule(request));
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900804 writer.AppendProtoAsArrayOfBytes(response);
805 return dbus_response;
806}
807
Jie Jiang25c1b972020-11-12 15:42:53 +0900808void Manager::OnNeighborReachabilityEvent(
Jie Jiang84966852020-09-18 18:49:05 +0900809 int ifindex,
810 const shill::IPAddress& ip_addr,
811 NeighborLinkMonitor::NeighborRole role,
Jie Jiang25c1b972020-11-12 15:42:53 +0900812 NeighborReachabilityEventSignal::EventType event_type) {
Jie Jiang84966852020-09-18 18:49:05 +0900813 if (!ip_addr.IsValid()) {
814 LOG(DFATAL) << "ip_addr is not valid";
815 return;
816 }
817
Jie Jiang25c1b972020-11-12 15:42:53 +0900818 using SignalProto = NeighborReachabilityEventSignal;
Jie Jiang84966852020-09-18 18:49:05 +0900819 SignalProto proto;
820 proto.set_ifindex(ifindex);
821 proto.set_ip_addr(ip_addr.ToString());
Jie Jiang25c1b972020-11-12 15:42:53 +0900822 proto.set_type(event_type);
Jie Jiang84966852020-09-18 18:49:05 +0900823 switch (role) {
824 case NeighborLinkMonitor::NeighborRole::kGateway:
825 proto.set_role(SignalProto::GATEWAY);
826 break;
827 case NeighborLinkMonitor::NeighborRole::kDNSServer:
828 proto.set_role(SignalProto::DNS_SERVER);
829 break;
830 case NeighborLinkMonitor::NeighborRole::kGatewayAndDNSServer:
831 proto.set_role(SignalProto::GATEWAY_AND_DNS_SERVER);
832 break;
833 default:
834 NOTREACHED();
835 }
836
Jie Jiang25c1b972020-11-12 15:42:53 +0900837 dbus::Signal signal(kPatchPanelInterface, kNeighborReachabilityEventSignal);
Jie Jiang84966852020-09-18 18:49:05 +0900838 dbus::MessageWriter writer(&signal);
839 if (!writer.AppendProtoAsArrayOfBytes(proto)) {
Jie Jiang25c1b972020-11-12 15:42:53 +0900840 LOG(ERROR) << "Failed to encode proto NeighborReachabilityEventSignal";
Jie Jiang84966852020-09-18 18:49:05 +0900841 return;
842 }
843
844 dbus_svc_path_->SendSignal(&signal);
845}
846
Hugo Benichi7c342672020-09-08 09:18:14 +0900847std::unique_ptr<patchpanel::ConnectNamespaceResponse> Manager::ConnectNamespace(
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900848 base::ScopedFD client_fd,
Hugo Benichi7c342672020-09-08 09:18:14 +0900849 const patchpanel::ConnectNamespaceRequest& request) {
850 auto response = std::make_unique<patchpanel::ConnectNamespaceResponse>();
851
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900852 std::unique_ptr<Subnet> subnet =
853 addr_mgr_.AllocateIPv4Subnet(AddressManager::Guest::MINIJAIL_NETNS);
854 if (!subnet) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900855 LOG(ERROR) << "ConnectNamespace: exhausted IPv4 subnet space";
856 return response;
Hugo Benichie8758b52020-04-03 14:49:01 +0900857 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900858
Hugo Benichi7352ad92020-04-07 16:11:59 +0900859 // Dup the client fd into our own: this guarantees that the fd number will
860 // be stable and tied to the actual kernel resources used by the client.
861 base::ScopedFD local_client_fd(dup(client_fd.get()));
862 if (!local_client_fd.is_valid()) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900863 PLOG(ERROR) << "ConnectNamespace: failed to dup() client fd";
864 return response;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900865 }
866
Hugo Benichi7c342672020-09-08 09:18:14 +0900867 // Add the duped fd to the epoll watcher.
Hugo Benichi7352ad92020-04-07 16:11:59 +0900868 // TODO(hugobenichi) Find a way to reuse base::FileDescriptorWatcher for
869 // listening to EPOLLHUP.
870 struct epoll_event epevent;
871 epevent.events = EPOLLIN; // EPOLLERR | EPOLLHUP are always waited for.
872 epevent.data.fd = local_client_fd.get();
873 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_ADD,
874 local_client_fd.get(), &epevent) != 0) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900875 PLOG(ERROR) << "ConnectNamespace: epoll_ctl(EPOLL_CTL_ADD) failed";
876 return response;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900877 }
878
Hugo Benichi7c342672020-09-08 09:18:14 +0900879 const std::string ifname_id = std::to_string(connected_namespaces_next_id_);
880 const std::string netns_name = "connected_netns_" + ifname_id;
881 const std::string host_ifname = "arc_ns" + ifname_id;
882 const std::string client_ifname = "veth" + ifname_id;
883 if (!datapath_->StartRoutingNamespace(
884 request.pid(), netns_name, host_ifname, client_ifname,
885 subnet->BaseAddress(), subnet->PrefixLength(),
886 subnet->AddressAtOffset(0), subnet->AddressAtOffset(1),
887 addr_mgr_.GenerateMacAddress())) {
888 LOG(ERROR) << "ConnectNamespace: failed to setup datapath";
889 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL,
890 local_client_fd.get(), nullptr) != 0)
891 PLOG(ERROR) << "ConnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
892 return response;
893 }
894
895 // TODO(hugobenichi) The peer and host addresses are swapped in the response
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900896 // Prepare the response before storing ConnectNamespaceInfo.
Hugo Benichi7c342672020-09-08 09:18:14 +0900897 response->set_peer_ifname(client_ifname);
898 response->set_peer_ipv4_address(subnet->AddressAtOffset(0));
899 response->set_host_ifname(host_ifname);
900 response->set_host_ipv4_address(subnet->AddressAtOffset(1));
901 auto* response_subnet = response->mutable_ipv4_subnet();
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900902 response_subnet->set_base_addr(subnet->BaseAddress());
903 response_subnet->set_prefix_len(subnet->PrefixLength());
904
905 // Store ConnectNamespaceInfo
906 connected_namespaces_next_id_++;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900907 int fdkey = local_client_fd.release();
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900908 connected_namespaces_[fdkey] = {};
909 ConnectNamespaceInfo& ns_info = connected_namespaces_[fdkey];
910 ns_info.pid = request.pid();
Hugo Benichi33860d72020-07-09 16:34:01 +0900911 ns_info.netns_name = std::move(netns_name);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900912 ns_info.outbound_ifname = request.outbound_physical_device();
913 ns_info.host_ifname = std::move(host_ifname);
914 ns_info.client_ifname = std::move(client_ifname);
915 ns_info.client_subnet = std::move(subnet);
916
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900917 LOG(INFO) << "Connected network namespace " << ns_info;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900918
919 if (connected_namespaces_.size() == 1) {
920 LOG(INFO) << "Starting ConnectNamespace client fds monitoring";
921 CheckConnectedNamespaces();
922 }
Hugo Benichi7c342672020-09-08 09:18:14 +0900923
924 return response;
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900925}
926
927void Manager::DisconnectNamespace(int client_fd) {
928 auto it = connected_namespaces_.find(client_fd);
929 if (it == connected_namespaces_.end()) {
930 LOG(ERROR) << "No ConnectNamespaceInfo found for client_fd " << client_fd;
931 return;
932 }
933
Hugo Benichi7352ad92020-04-07 16:11:59 +0900934 // Remove the client fd dupe from the epoll watcher and close it.
935 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL, client_fd,
Hugo Benichie8758b52020-04-03 14:49:01 +0900936 nullptr) != 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900937 PLOG(ERROR) << "DisconnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900938 if (close(client_fd) < 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900939 PLOG(ERROR) << "DisconnectNamespace: close(client_fd) failed";
Hugo Benichi7352ad92020-04-07 16:11:59 +0900940
Hugo Benichi7c342672020-09-08 09:18:14 +0900941 datapath_->StopRoutingNamespace(it->second.netns_name, it->second.host_ifname,
942 it->second.client_subnet->BaseAddress(),
943 it->second.client_subnet->PrefixLength(),
944 it->second.client_subnet->AddressAtOffset(0));
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900945
946 LOG(INFO) << "Disconnected network namespace " << it->second;
947
948 // This release the allocated IPv4 subnet.
949 connected_namespaces_.erase(it);
950}
951
Hugo Benichi7352ad92020-04-07 16:11:59 +0900952// TODO(hugobenichi) Generalize this check to all resources created by
953// patchpanel on behalf of a remote client.
954void Manager::CheckConnectedNamespaces() {
955 int max_event = 10;
956 struct epoll_event epevents[max_event];
957 int nready = epoll_wait(connected_namespaces_epollfd_, epevents, max_event,
958 0 /* do not block */);
959 if (nready < 0)
960 PLOG(ERROR) << "CheckConnectedNamespaces: epoll_wait(0) failed";
961
962 for (int i = 0; i < nready; i++)
963 if (epevents[i].events & (EPOLLHUP | EPOLLERR))
964 DisconnectNamespace(epevents[i].data.fd);
965
966 if (connected_namespaces_.empty()) {
967 LOG(INFO) << "Stopping ConnectNamespace client fds monitoring";
968 return;
969 }
970
Qijiang Fan2d7aeb42020-05-19 02:06:39 +0900971 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Hugo Benichi7352ad92020-04-07 16:11:59 +0900972 FROM_HERE,
973 base::Bind(&Manager::CheckConnectedNamespaces,
Hugo Benichie8758b52020-04-03 14:49:01 +0900974 weak_factory_.GetWeakPtr()),
Hugo Benichi7352ad92020-04-07 16:11:59 +0900975 kConnectNamespaceCheckInterval);
976}
977
Jason Jeremy Imanc28df852020-07-11 17:38:26 +0900978bool Manager::ModifyPortRule(const patchpanel::ModifyPortRuleRequest& request) {
979 switch (request.proto()) {
980 case patchpanel::ModifyPortRuleRequest::TCP:
981 case patchpanel::ModifyPortRuleRequest::UDP:
982 break;
983 default:
984 LOG(ERROR) << "Unknown protocol " << request.proto();
985 return false;
986 }
987
988 switch (request.op()) {
989 case patchpanel::ModifyPortRuleRequest::CREATE:
990 switch (request.type()) {
991 case patchpanel::ModifyPortRuleRequest::ACCESS:
992 return firewall_.AddAcceptRules(request.proto(),
993 request.input_dst_port(),
994 request.input_ifname());
995 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
996 return firewall_.AddLoopbackLockdownRules(request.proto(),
997 request.input_dst_port());
998 case patchpanel::ModifyPortRuleRequest::FORWARDING:
999 return firewall_.AddIpv4ForwardRule(
1000 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1001 request.input_ifname(), request.dst_ip(), request.dst_port());
1002 default:
1003 LOG(ERROR) << "Unknown port rule type " << request.type();
1004 return false;
1005 }
1006 case patchpanel::ModifyPortRuleRequest::DELETE:
1007 switch (request.type()) {
1008 case patchpanel::ModifyPortRuleRequest::ACCESS:
1009 return firewall_.DeleteAcceptRules(request.proto(),
1010 request.input_dst_port(),
1011 request.input_ifname());
1012 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
1013 return firewall_.DeleteLoopbackLockdownRules(
1014 request.proto(), request.input_dst_port());
1015 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1016 return firewall_.DeleteIpv4ForwardRule(
1017 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1018 request.input_ifname(), request.dst_ip(), request.dst_port());
1019 default:
1020 LOG(ERROR) << "Unknown port rule type " << request.type();
1021 return false;
1022 }
1023 default:
1024 LOG(ERROR) << "Unknown operation " << request.op();
1025 return false;
1026 }
1027}
1028
Garrick Evanse94a14e2019-11-11 10:32:13 +09001029void Manager::SendGuestMessage(const GuestMessage& msg) {
Garrick Evans96e03042019-05-28 14:30:52 +09001030 IpHelperMessage ipm;
1031 *ipm.mutable_guest_message() = msg;
Garrick Evans96e03042019-05-28 14:30:52 +09001032 adb_proxy_->SendMessage(ipm);
Garrick Evanse94a14e2019-11-11 10:32:13 +09001033 mcast_proxy_->SendMessage(ipm);
1034 nd_proxy_->SendMessage(ipm);
Garrick Evans96e03042019-05-28 14:30:52 +09001035}
1036
Garrick Evans4ac09852020-01-16 14:09:22 +09001037void Manager::StartForwarding(const std::string& ifname_physical,
1038 const std::string& ifname_virtual,
Garrick Evans4ac09852020-01-16 14:09:22 +09001039 bool ipv6,
1040 bool multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001041 if (ifname_physical.empty() || ifname_virtual.empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001042 return;
1043
1044 IpHelperMessage ipm;
1045 DeviceMessage* msg = ipm.mutable_device_message();
1046 msg->set_dev_ifname(ifname_physical);
Garrick Evans4ac09852020-01-16 14:09:22 +09001047 msg->set_br_ifname(ifname_virtual);
1048
1049 if (ipv6) {
1050 LOG(INFO) << "Starting IPv6 forwarding from " << ifname_physical << " to "
1051 << ifname_virtual;
1052
1053 if (!datapath_->AddIPv6Forwarding(ifname_physical, ifname_virtual)) {
1054 LOG(ERROR) << "Failed to setup iptables forwarding rule for IPv6 from "
1055 << ifname_physical << " to " << ifname_virtual;
1056 }
1057 if (!datapath_->MaskInterfaceFlags(ifname_physical, IFF_ALLMULTI)) {
1058 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1059 << ifname_physical;
1060 }
1061 if (!datapath_->MaskInterfaceFlags(ifname_virtual, IFF_ALLMULTI)) {
1062 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1063 << ifname_virtual;
1064 }
1065 nd_proxy_->SendMessage(ipm);
1066 }
1067
1068 if (multicast) {
1069 LOG(INFO) << "Starting multicast forwarding from " << ifname_physical
1070 << " to " << ifname_virtual;
1071 mcast_proxy_->SendMessage(ipm);
1072 }
1073}
1074
1075void Manager::StopForwarding(const std::string& ifname_physical,
1076 const std::string& ifname_virtual,
1077 bool ipv6,
1078 bool multicast) {
1079 if (ifname_physical.empty())
1080 return;
1081
1082 IpHelperMessage ipm;
1083 DeviceMessage* msg = ipm.mutable_device_message();
1084 msg->set_dev_ifname(ifname_physical);
1085 msg->set_teardown(true);
Taoyu Li7dca19a2020-03-16 16:27:07 +09001086 if (!ifname_virtual.empty()) {
1087 msg->set_br_ifname(ifname_virtual);
1088 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001089
1090 if (ipv6) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001091 if (ifname_virtual.empty()) {
1092 LOG(INFO) << "Stopping IPv6 forwarding on " << ifname_physical;
1093 } else {
1094 LOG(INFO) << "Stopping IPv6 forwarding from " << ifname_physical << " to "
1095 << ifname_virtual;
1096 datapath_->RemoveIPv6Forwarding(ifname_physical, ifname_virtual);
1097 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001098 nd_proxy_->SendMessage(ipm);
1099 }
1100
1101 if (multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001102 if (ifname_virtual.empty()) {
1103 LOG(INFO) << "Stopping multicast forwarding on " << ifname_physical;
1104 } else {
1105 LOG(INFO) << "Stopping multicast forwarding from " << ifname_physical
1106 << " to " << ifname_virtual;
1107 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001108 mcast_proxy_->SendMessage(ipm);
1109 }
1110}
1111
Taoyu Lia0727dc2020-09-24 19:54:59 +09001112void Manager::OnNDProxyMessage(const NDProxyMessage& msg) {
1113 LOG_IF(DFATAL, msg.ifname().empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001114 << "Received DeviceMessage w/ empty dev_ifname";
Taoyu Lia0727dc2020-09-24 19:54:59 +09001115 switch (msg.type()) {
1116 case NDProxyMessage::ADD_ROUTE:
1117 if (!datapath_->AddIPv6HostRoute(msg.ifname(), msg.ip6addr(), 128)) {
1118 LOG(WARNING) << "Failed to setup the IPv6 route for interface "
1119 << msg.ifname() << ", addr " << msg.ip6addr();
1120 }
1121 break;
1122 case NDProxyMessage::ADD_ADDR:
1123 if (!datapath_->AddIPv6Address(msg.ifname(), msg.ip6addr())) {
1124 LOG(WARNING) << "Failed to setup the IPv6 address for interface "
1125 << msg.ifname() << ", addr " << msg.ip6addr();
1126 }
1127 break;
1128 case NDProxyMessage::DEL_ADDR:
1129 datapath_->RemoveIPv6Address(msg.ifname(), msg.ip6addr());
1130 break;
1131 default:
1132 LOG(ERROR) << "Unknown NDProxy event " << msg.type();
1133 NOTREACHED();
Garrick Evans4ac09852020-01-16 14:09:22 +09001134 }
1135}
1136
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001137std::ostream& operator<<(std::ostream& stream,
1138 const Manager::ConnectNamespaceInfo& ns_info) {
1139 stream << "{ pid: " << ns_info.pid;
1140 if (!ns_info.outbound_ifname.empty()) {
1141 stream << ", outbound_ifname: " << ns_info.outbound_ifname;
1142 }
1143 stream << ", host_ifname: " << ns_info.host_ifname
1144 << ", client_ifname: " << ns_info.client_ifname
1145 << ", subnet: " << ns_info.client_subnet->ToCidrString() << '}';
1146 return stream;
1147}
1148
Garrick Evans3388a032020-03-24 11:25:55 +09001149} // namespace patchpanel