blob: 8562316631fc3330d97e99e96e8309411ea636f6 [file] [log] [blame]
Kevin Cernekee95d4ae92016-06-19 10:26:29 -07001// Copyright 2016 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Garrick Evans3388a032020-03-24 11:25:55 +09005#include "patchpanel/manager.h"
Kevin Cernekee4e62cc12016-12-03 11:50:53 -08006
Kevin Cernekee95d4ae92016-06-19 10:26:29 -07007#include <arpa/inet.h>
Garrick Evans4ac09852020-01-16 14:09:22 +09008#include <net/if.h>
Hugo Benichi935eca92018-07-03 13:47:24 +09009#include <netinet/in.h>
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070010#include <stdint.h>
Hugo Benichi7352ad92020-04-07 16:11:59 +090011#include <sys/epoll.h>
Garrick Evans54861622019-07-19 09:05:09 +090012#include <sys/prctl.h>
Garrick Evans96e03042019-05-28 14:30:52 +090013#include <sys/socket.h>
14#include <sys/un.h>
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070015
Kevin Cernekee27bcaa62016-12-03 11:16:26 -080016#include <utility>
17
Hugo Benichicc6850f2020-01-17 13:26:06 +090018#include <base/bind.h>
Taoyu Lia0727dc2020-09-24 19:54:59 +090019#include <base/files/scoped_file.h>
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070020#include <base/logging.h>
Taoyu Lic85c44b2019-12-04 17:32:57 +090021#include <base/strings/string_number_conversions.h>
Garrick Evans96e03042019-05-28 14:30:52 +090022#include <base/strings/string_split.h>
Garrick Evans6f258d02019-06-28 16:32:07 +090023#include <base/strings/string_util.h>
Taoyu Li179dcc62019-10-17 11:21:08 +090024#include <base/strings/stringprintf.h>
hschamf9546312020-04-14 15:12:40 +090025#include <base/threading/thread_task_runner_handle.h>
Taoyu Lic85c44b2019-12-04 17:32:57 +090026#include <brillo/key_value_store.h>
Kevin Cernekee27bcaa62016-12-03 11:16:26 -080027#include <brillo/minijail/minijail.h>
28
Garrick Evans3388a032020-03-24 11:25:55 +090029#include "patchpanel/ipc.pb.h"
30#include "patchpanel/mac_address_generator.h"
31#include "patchpanel/net_util.h"
32#include "patchpanel/routing_service.h"
33#include "patchpanel/scoped_ns.h"
Garrick Evans428e4762018-12-11 15:18:42 +090034
Garrick Evans3388a032020-03-24 11:25:55 +090035namespace patchpanel {
Garrick Evans08843932019-09-17 14:41:08 +090036namespace {
Garrick Evans4c042572019-12-17 13:42:25 +090037constexpr int kSubprocessRestartDelayMs = 900;
Garrick Evans08843932019-09-17 14:41:08 +090038
Hugo Benichi7352ad92020-04-07 16:11:59 +090039// Time interval between epoll checks on file descriptors committed by callers
40// of ConnectNamespace DBus API.
41constexpr const base::TimeDelta kConnectNamespaceCheckInterval =
Hugo Benichifa9462e2020-06-26 09:50:48 +090042 base::TimeDelta::FromSeconds(5);
Hugo Benichi7352ad92020-04-07 16:11:59 +090043
Garrick Evans08843932019-09-17 14:41:08 +090044// Passes |method_call| to |handler| and passes the response to
45// |response_sender|. If |handler| returns nullptr, an empty response is
46// created and sent.
47void HandleSynchronousDBusMethodCall(
48 base::Callback<std::unique_ptr<dbus::Response>(dbus::MethodCall*)> handler,
49 dbus::MethodCall* method_call,
50 dbus::ExportedObject::ResponseSender response_sender) {
51 std::unique_ptr<dbus::Response> response = handler.Run(method_call);
52 if (!response)
53 response = dbus::Response::FromMethodCall(method_call);
Qijiang Fan0c657d42020-08-24 19:07:50 +090054 std::move(response_sender).Run(std::move(response));
Garrick Evans08843932019-09-17 14:41:08 +090055}
56
57} // namespace
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070058
Taoyu Lice7caa62019-10-01 15:43:33 +090059Manager::Manager(std::unique_ptr<HelperProcess> adb_proxy,
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090060 std::unique_ptr<HelperProcess> mcast_proxy,
Garrick Evans1f5a3612019-11-08 12:59:03 +090061 std::unique_ptr<HelperProcess> nd_proxy)
Garrick Evans3915af32019-07-25 15:44:34 +090062 : adb_proxy_(std::move(adb_proxy)),
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090063 mcast_proxy_(std::move(mcast_proxy)),
Garrick Evans4ee5ce22020-03-18 07:05:17 +090064 nd_proxy_(std::move(nd_proxy)) {
Taoyu Li179dcc62019-10-17 11:21:08 +090065 runner_ = std::make_unique<MinijailedProcessRunner>();
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090066 datapath_ = std::make_unique<Datapath>(runner_.get(), &firewall_);
Hugo Benichi7352ad92020-04-07 16:11:59 +090067 connected_namespaces_epollfd_ = epoll_create(1 /* size */);
Taoyu Li179dcc62019-10-17 11:21:08 +090068}
Long Chengd4415582019-09-24 19:16:09 +000069
Garrick Evans207e7482019-12-16 11:54:36 +090070Manager::~Manager() {
71 OnShutdown(nullptr);
72}
73
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +090074std::map<const std::string, bool> Manager::cached_feature_enabled_ = {};
75
76bool Manager::ShouldEnableFeature(
77 int min_android_sdk_version,
78 int min_chrome_milestone,
79 const std::vector<std::string>& supported_boards,
80 const std::string& feature_name) {
81 static const char kLsbReleasePath[] = "/etc/lsb-release";
82
83 const auto& cached_result = cached_feature_enabled_.find(feature_name);
84 if (cached_result != cached_feature_enabled_.end())
85 return cached_result->second;
86
87 auto check = [min_android_sdk_version, min_chrome_milestone,
88 &supported_boards, &feature_name]() {
89 brillo::KeyValueStore store;
90 if (!store.Load(base::FilePath(kLsbReleasePath))) {
91 LOG(ERROR) << "Could not read lsb-release";
92 return false;
93 }
94
95 std::string value;
96 if (!store.GetString("CHROMEOS_ARC_ANDROID_SDK_VERSION", &value)) {
97 LOG(ERROR) << feature_name
98 << " disabled - cannot determine Android SDK version";
99 return false;
100 }
101 int ver = 0;
102 if (!base::StringToInt(value.c_str(), &ver)) {
103 LOG(ERROR) << feature_name << " disabled - invalid Android SDK version";
104 return false;
105 }
106 if (ver < min_android_sdk_version) {
107 LOG(INFO) << feature_name << " disabled for Android SDK " << value;
108 return false;
109 }
110
111 if (!store.GetString("CHROMEOS_RELEASE_CHROME_MILESTONE", &value)) {
112 LOG(ERROR) << feature_name
113 << " disabled - cannot determine ChromeOS milestone";
114 return false;
115 }
116 if (!base::StringToInt(value.c_str(), &ver)) {
117 LOG(ERROR) << feature_name << " disabled - invalid ChromeOS milestone";
118 return false;
119 }
120 if (ver < min_chrome_milestone) {
121 LOG(INFO) << feature_name << " disabled for ChromeOS milestone " << value;
122 return false;
123 }
124
125 if (!store.GetString("CHROMEOS_RELEASE_BOARD", &value)) {
126 LOG(ERROR) << feature_name << " disabled - cannot determine board";
127 return false;
128 }
129 if (!supported_boards.empty() &&
130 std::find(supported_boards.begin(), supported_boards.end(), value) ==
131 supported_boards.end()) {
132 LOG(INFO) << feature_name << " disabled for board " << value;
133 return false;
134 }
135 return true;
136 };
137
138 bool result = check();
139 cached_feature_enabled_.emplace(feature_name, result);
140 return result;
141}
142
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700143int Manager::OnInit() {
Garrick Evans54861622019-07-19 09:05:09 +0900144 prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800145
146 // Handle subprocess lifecycle.
147 process_reaper_.Register(this);
Hugo Benichi935eca92018-07-03 13:47:24 +0900148
149 CHECK(process_reaper_.WatchForChild(
Garrick Evans96e03042019-05-28 14:30:52 +0900150 FROM_HERE, adb_proxy_->pid(),
151 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
152 adb_proxy_->pid())))
153 << "Failed to watch adb-proxy child process";
Taoyu Liaf944c92019-10-01 12:22:31 +0900154 CHECK(process_reaper_.WatchForChild(
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900155 FROM_HERE, mcast_proxy_->pid(),
156 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
157 nd_proxy_->pid())))
158 << "Failed to watch multicast-proxy child process";
159 CHECK(process_reaper_.WatchForChild(
Taoyu Liaf944c92019-10-01 12:22:31 +0900160 FROM_HERE, nd_proxy_->pid(),
161 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
162 nd_proxy_->pid())))
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900163 << "Failed to watch nd-proxy child process";
Garrick Evans96e03042019-05-28 14:30:52 +0900164
Garrick Evans49879532018-12-03 13:15:36 +0900165 // Run after Daemon::OnInit().
hschamf9546312020-04-14 15:12:40 +0900166 base::ThreadTaskRunnerHandle::Get()->PostTask(
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700167 FROM_HERE,
168 base::Bind(&Manager::InitialSetup, weak_factory_.GetWeakPtr()));
169
170 return DBusDaemon::OnInit();
171}
172
173void Manager::InitialSetup() {
Garrick Evans08843932019-09-17 14:41:08 +0900174 LOG(INFO) << "Setting up DBus service interface";
175 dbus_svc_path_ = bus_->GetExportedObject(
176 dbus::ObjectPath(patchpanel::kPatchPanelServicePath));
177 if (!dbus_svc_path_) {
178 LOG(FATAL) << "Failed to export " << patchpanel::kPatchPanelServicePath
179 << " object";
180 }
181
Hugo Benichi76be34a2020-08-26 22:35:54 +0900182 shill_client_ = std::make_unique<ShillClient>(bus_);
183
Garrick Evans08843932019-09-17 14:41:08 +0900184 using ServiceMethod =
185 std::unique_ptr<dbus::Response> (Manager::*)(dbus::MethodCall*);
186 const std::map<const char*, ServiceMethod> kServiceMethods = {
187 {patchpanel::kArcStartupMethod, &Manager::OnArcStartup},
188 {patchpanel::kArcShutdownMethod, &Manager::OnArcShutdown},
189 {patchpanel::kArcVmStartupMethod, &Manager::OnArcVmStartup},
190 {patchpanel::kArcVmShutdownMethod, &Manager::OnArcVmShutdown},
Garrick Evans47c19272019-11-21 10:58:21 +0900191 {patchpanel::kTerminaVmStartupMethod, &Manager::OnTerminaVmStartup},
192 {patchpanel::kTerminaVmShutdownMethod, &Manager::OnTerminaVmShutdown},
Garrick Evans51d5b552020-01-30 10:42:06 +0900193 {patchpanel::kPluginVmStartupMethod, &Manager::OnPluginVmStartup},
194 {patchpanel::kPluginVmShutdownMethod, &Manager::OnPluginVmShutdown},
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900195 {patchpanel::kSetVpnIntentMethod, &Manager::OnSetVpnIntent},
Hugo Benichib56b77c2020-01-15 16:00:56 +0900196 {patchpanel::kConnectNamespaceMethod, &Manager::OnConnectNamespace},
Jie Jiang493cde42020-07-17 21:43:39 +0900197 {patchpanel::kGetTrafficCountersMethod, &Manager::OnGetTrafficCounters},
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900198 {patchpanel::kModifyPortRuleMethod, &Manager::OnModifyPortRule},
Garrick Evans08843932019-09-17 14:41:08 +0900199 };
200
201 for (const auto& kv : kServiceMethods) {
202 if (!dbus_svc_path_->ExportMethodAndBlock(
203 patchpanel::kPatchPanelInterface, kv.first,
204 base::Bind(&HandleSynchronousDBusMethodCall,
205 base::Bind(kv.second, base::Unretained(this))))) {
206 LOG(FATAL) << "Failed to export method " << kv.first;
207 }
208 }
209
210 if (!bus_->RequestOwnershipAndBlock(patchpanel::kPatchPanelServiceName,
211 dbus::Bus::REQUIRE_PRIMARY)) {
212 LOG(FATAL) << "Failed to take ownership of "
213 << patchpanel::kPatchPanelServiceName;
214 }
215 LOG(INFO) << "DBus service interface ready";
216
Hugo Benichifda77232020-08-21 18:28:15 +0900217 routing_svc_ = std::make_unique<RoutingService>();
218
Hugo Benichibf811c62020-09-07 17:30:45 +0900219 // b/162966185: Allow Jetstream to disable:
220 // - the IP forwarding setup used for hosting VMs and containers,
221 // - the iptables rules for fwmark based routing.
222 if (!USE_JETSTREAM_ROUTING) {
223 datapath_->Start();
224 shill_client_->RegisterDevicesChangedHandler(base::BindRepeating(
225 &Manager::OnDevicesChanged, weak_factory_.GetWeakPtr()));
226 }
Hugo Benichifda77232020-08-21 18:28:15 +0900227
Taoyu Lia0727dc2020-09-24 19:54:59 +0900228 nd_proxy_->RegisterNDProxyMessageHandler(
229 base::Bind(&Manager::OnNDProxyMessage, weak_factory_.GetWeakPtr()));
Hugo Benichifda77232020-08-21 18:28:15 +0900230
Hugo Benichifda77232020-08-21 18:28:15 +0900231 auto* const forwarder = static_cast<TrafficForwarder*>(this);
232
233 GuestMessage::GuestType arc_guest =
234 USE_ARCVM ? GuestMessage::ARC_VM : GuestMessage::ARC;
235 arc_svc_ = std::make_unique<ArcService>(shill_client_.get(), datapath_.get(),
236 &addr_mgr_, forwarder, arc_guest);
237 cros_svc_ = std::make_unique<CrostiniService>(shill_client_.get(), &addr_mgr_,
238 datapath_.get(), forwarder);
Jie Jiang84966852020-09-18 18:49:05 +0900239 network_monitor_svc_ = std::make_unique<NetworkMonitorService>(
240 shill_client_.get(),
241 base::BindRepeating(&Manager::OnNeighborConnectedStateChanged,
242 weak_factory_.GetWeakPtr()));
Hugo Benichifda77232020-08-21 18:28:15 +0900243 network_monitor_svc_->Start();
244
245 counters_svc_ =
246 std::make_unique<CountersService>(shill_client_.get(), runner_.get());
247
248 nd_proxy_->Listen();
249}
250
251void Manager::OnShutdown(int* exit_code) {
252 LOG(INFO) << "Shutting down and cleaning up";
Jie Jiang84966852020-09-18 18:49:05 +0900253 network_monitor_svc_.reset();
Hugo Benichifda77232020-08-21 18:28:15 +0900254 cros_svc_.reset();
255 arc_svc_.reset();
256 close(connected_namespaces_epollfd_);
257 // Tear down any remaining connected namespace.
258 std::vector<int> connected_namespaces_fdkeys;
259 for (const auto& kv : connected_namespaces_)
260 connected_namespaces_fdkeys.push_back(kv.first);
261 for (const int fdkey : connected_namespaces_fdkeys)
262 DisconnectNamespace(fdkey);
Hugo Benichibf811c62020-09-07 17:30:45 +0900263 if (!USE_JETSTREAM_ROUTING)
264 datapath_->Stop();
Hugo Benichifda77232020-08-21 18:28:15 +0900265}
266
267void Manager::OnSubprocessExited(pid_t pid, const siginfo_t&) {
268 LOG(ERROR) << "Subprocess " << pid << " exited unexpectedly -"
269 << " attempting to restart";
270
271 HelperProcess* proc;
272 if (pid == adb_proxy_->pid()) {
273 proc = adb_proxy_.get();
274 } else if (pid == mcast_proxy_->pid()) {
275 proc = mcast_proxy_.get();
276 } else if (pid == nd_proxy_->pid()) {
277 proc = nd_proxy_.get();
278 } else {
279 LOG(DFATAL) << "Unknown child process";
280 return;
281 }
282
283 process_reaper_.ForgetChild(pid);
284
285 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
286 FROM_HERE,
287 base::Bind(&Manager::RestartSubprocess, weak_factory_.GetWeakPtr(), proc),
288 base::TimeDelta::FromMilliseconds((2 << proc->restarts()) *
289 kSubprocessRestartDelayMs));
290}
291
292void Manager::RestartSubprocess(HelperProcess* subproc) {
293 if (subproc->Restart()) {
294 DCHECK(process_reaper_.WatchForChild(
295 FROM_HERE, subproc->pid(),
296 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
297 subproc->pid())))
298 << "Failed to watch child process " << subproc->pid();
299 }
300}
301
Hugo Benichi76be34a2020-08-26 22:35:54 +0900302void Manager::OnDevicesChanged(const std::set<std::string>& added,
303 const std::set<std::string>& removed) {
304 for (const std::string& ifname : removed)
305 datapath_->StopConnectionPinning(ifname);
306
307 for (const std::string& ifname : added)
308 datapath_->StartConnectionPinning(ifname);
309}
310
Garrick Evanse94a14e2019-11-11 10:32:13 +0900311bool Manager::StartArc(pid_t pid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900312 if (!arc_svc_->Start(pid))
313 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900314
315 GuestMessage msg;
316 msg.set_event(GuestMessage::START);
317 msg.set_type(GuestMessage::ARC);
318 msg.set_arc_pid(pid);
319 SendGuestMessage(msg);
320
321 return true;
322}
323
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900324void Manager::StopArc() {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900325 GuestMessage msg;
326 msg.set_event(GuestMessage::STOP);
327 msg.set_type(GuestMessage::ARC);
328 SendGuestMessage(msg);
329
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900330 // After the ARC container has stopped, the pid is not known anymore.
331 // The pid argument is ignored by ArcService.
332 arc_svc_->Stop(0);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900333}
334
Garrick Evans015b0d62020-02-07 09:06:38 +0900335bool Manager::StartArcVm(uint32_t cid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900336 if (!arc_svc_->Start(cid))
337 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900338
339 GuestMessage msg;
340 msg.set_event(GuestMessage::START);
341 msg.set_type(GuestMessage::ARC_VM);
342 msg.set_arcvm_vsock_cid(cid);
343 SendGuestMessage(msg);
344
345 return true;
346}
347
Garrick Evans015b0d62020-02-07 09:06:38 +0900348void Manager::StopArcVm(uint32_t cid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900349 GuestMessage msg;
350 msg.set_event(GuestMessage::STOP);
351 msg.set_type(GuestMessage::ARC_VM);
352 SendGuestMessage(msg);
353
Garrick Evans21173b12019-11-20 15:23:16 +0900354 arc_svc_->Stop(cid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900355}
356
Garrick Evans51d5b552020-01-30 10:42:06 +0900357bool Manager::StartCrosVm(uint64_t vm_id,
358 GuestMessage::GuestType vm_type,
Garrick Evans53a2a982020-02-05 10:53:35 +0900359 uint32_t subnet_index) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900360 DCHECK(vm_type == GuestMessage::TERMINA_VM ||
361 vm_type == GuestMessage::PLUGIN_VM);
362
363 if (!cros_svc_->Start(vm_id, vm_type == GuestMessage::TERMINA_VM,
364 subnet_index))
Garrick Evans47c19272019-11-21 10:58:21 +0900365 return false;
366
367 GuestMessage msg;
368 msg.set_event(GuestMessage::START);
Garrick Evans51d5b552020-01-30 10:42:06 +0900369 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900370 SendGuestMessage(msg);
371
372 return true;
373}
374
Garrick Evans51d5b552020-01-30 10:42:06 +0900375void Manager::StopCrosVm(uint64_t vm_id, GuestMessage::GuestType vm_type) {
Garrick Evans47c19272019-11-21 10:58:21 +0900376 GuestMessage msg;
377 msg.set_event(GuestMessage::STOP);
Garrick Evans51d5b552020-01-30 10:42:06 +0900378 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900379 SendGuestMessage(msg);
380
Garrick Evans51d5b552020-01-30 10:42:06 +0900381 cros_svc_->Stop(vm_id, vm_type == GuestMessage::TERMINA_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900382}
383
Garrick Evans08843932019-09-17 14:41:08 +0900384std::unique_ptr<dbus::Response> Manager::OnArcStartup(
385 dbus::MethodCall* method_call) {
386 LOG(INFO) << "ARC++ starting up";
387
388 std::unique_ptr<dbus::Response> dbus_response(
389 dbus::Response::FromMethodCall(method_call));
390
391 dbus::MessageReader reader(method_call);
392 dbus::MessageWriter writer(dbus_response.get());
393
394 patchpanel::ArcStartupRequest request;
395 patchpanel::ArcStartupResponse response;
396
397 if (!reader.PopArrayOfBytesAsProto(&request)) {
398 LOG(ERROR) << "Unable to parse request";
399 writer.AppendProtoAsArrayOfBytes(response);
400 return dbus_response;
401 }
402
Garrick Evanse01bf072019-11-15 09:08:19 +0900403 if (!StartArc(request.pid()))
404 LOG(ERROR) << "Failed to start ARC++ network service";
Garrick Evanse94a14e2019-11-11 10:32:13 +0900405
Garrick Evans08843932019-09-17 14:41:08 +0900406 writer.AppendProtoAsArrayOfBytes(response);
407 return dbus_response;
408}
409
410std::unique_ptr<dbus::Response> Manager::OnArcShutdown(
411 dbus::MethodCall* method_call) {
412 LOG(INFO) << "ARC++ shutting down";
413
414 std::unique_ptr<dbus::Response> dbus_response(
415 dbus::Response::FromMethodCall(method_call));
416
417 dbus::MessageReader reader(method_call);
418 dbus::MessageWriter writer(dbus_response.get());
419
420 patchpanel::ArcShutdownRequest request;
421 patchpanel::ArcShutdownResponse response;
422
423 if (!reader.PopArrayOfBytesAsProto(&request)) {
424 LOG(ERROR) << "Unable to parse request";
425 writer.AppendProtoAsArrayOfBytes(response);
426 return dbus_response;
427 }
428
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900429 StopArc();
Garrick Evanse94a14e2019-11-11 10:32:13 +0900430
Garrick Evans08843932019-09-17 14:41:08 +0900431 writer.AppendProtoAsArrayOfBytes(response);
432 return dbus_response;
433}
434
435std::unique_ptr<dbus::Response> Manager::OnArcVmStartup(
436 dbus::MethodCall* method_call) {
437 LOG(INFO) << "ARCVM starting up";
438
439 std::unique_ptr<dbus::Response> dbus_response(
440 dbus::Response::FromMethodCall(method_call));
441
442 dbus::MessageReader reader(method_call);
443 dbus::MessageWriter writer(dbus_response.get());
444
445 patchpanel::ArcVmStartupRequest request;
446 patchpanel::ArcVmStartupResponse response;
447
448 if (!reader.PopArrayOfBytesAsProto(&request)) {
449 LOG(ERROR) << "Unable to parse request";
450 writer.AppendProtoAsArrayOfBytes(response);
451 return dbus_response;
452 }
453
Garrick Evans47c19272019-11-21 10:58:21 +0900454 if (!StartArcVm(request.cid())) {
Garrick Evanse01bf072019-11-15 09:08:19 +0900455 LOG(ERROR) << "Failed to start ARCVM network service";
Garrick Evans47c19272019-11-21 10:58:21 +0900456 writer.AppendProtoAsArrayOfBytes(response);
457 return dbus_response;
Garrick Evanse01bf072019-11-15 09:08:19 +0900458 }
Garrick Evanse94a14e2019-11-11 10:32:13 +0900459
Garrick Evans47c19272019-11-21 10:58:21 +0900460 // Populate the response with the known devices.
Garrick Evans38b25a42020-04-06 15:17:42 +0900461 for (const auto* config : arc_svc_->GetDeviceConfigs()) {
462 if (config->tap_ifname().empty())
463 continue;
Garrick Evans47c19272019-11-21 10:58:21 +0900464
Garrick Evans38b25a42020-04-06 15:17:42 +0900465 auto* dev = response.add_devices();
466 dev->set_ifname(config->tap_ifname());
467 dev->set_ipv4_addr(config->guest_ipv4_addr());
468 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900469
Garrick Evans08843932019-09-17 14:41:08 +0900470 writer.AppendProtoAsArrayOfBytes(response);
471 return dbus_response;
472}
473
474std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
475 dbus::MethodCall* method_call) {
476 LOG(INFO) << "ARCVM shutting down";
477
478 std::unique_ptr<dbus::Response> dbus_response(
479 dbus::Response::FromMethodCall(method_call));
480
481 dbus::MessageReader reader(method_call);
482 dbus::MessageWriter writer(dbus_response.get());
483
484 patchpanel::ArcVmShutdownRequest request;
485 patchpanel::ArcVmShutdownResponse response;
486
487 if (!reader.PopArrayOfBytesAsProto(&request)) {
488 LOG(ERROR) << "Unable to parse request";
489 writer.AppendProtoAsArrayOfBytes(response);
490 return dbus_response;
491 }
492
Garrick Evans21173b12019-11-20 15:23:16 +0900493 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900494
Garrick Evans08843932019-09-17 14:41:08 +0900495 writer.AppendProtoAsArrayOfBytes(response);
496 return dbus_response;
497}
498
Garrick Evans47c19272019-11-21 10:58:21 +0900499std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
500 dbus::MethodCall* method_call) {
501 LOG(INFO) << "Termina VM starting up";
502
503 std::unique_ptr<dbus::Response> dbus_response(
504 dbus::Response::FromMethodCall(method_call));
505
506 dbus::MessageReader reader(method_call);
507 dbus::MessageWriter writer(dbus_response.get());
508
509 patchpanel::TerminaVmStartupRequest request;
510 patchpanel::TerminaVmStartupResponse response;
511
512 if (!reader.PopArrayOfBytesAsProto(&request)) {
513 LOG(ERROR) << "Unable to parse request";
514 writer.AppendProtoAsArrayOfBytes(response);
515 return dbus_response;
516 }
517
518 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900519 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900520 LOG(ERROR) << "Failed to start Termina VM network service";
521 writer.AppendProtoAsArrayOfBytes(response);
522 return dbus_response;
523 }
524
Garrick Evans51d5b552020-01-30 10:42:06 +0900525 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900526 if (!tap) {
527 LOG(DFATAL) << "TAP device missing";
528 writer.AppendProtoAsArrayOfBytes(response);
529 return dbus_response;
530 }
Garrick Evans47c19272019-11-21 10:58:21 +0900531
Garrick Evansb1c93712020-01-22 09:28:25 +0900532 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900533 dev->set_ifname(tap->host_ifname());
534 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900535 if (!subnet) {
536 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
537 writer.AppendProtoAsArrayOfBytes(response);
538 return dbus_response;
539 }
540 auto* resp_subnet = dev->mutable_ipv4_subnet();
541 resp_subnet->set_base_addr(subnet->BaseAddress());
542 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900543 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900544 if (!subnet) {
545 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
546 writer.AppendProtoAsArrayOfBytes(response);
547 return dbus_response;
548 }
549 resp_subnet = response.mutable_container_subnet();
550 resp_subnet->set_base_addr(subnet->BaseAddress());
551 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900552
553 writer.AppendProtoAsArrayOfBytes(response);
554 return dbus_response;
555}
556
557std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
558 dbus::MethodCall* method_call) {
559 LOG(INFO) << "Termina VM shutting down";
560
561 std::unique_ptr<dbus::Response> dbus_response(
562 dbus::Response::FromMethodCall(method_call));
563
564 dbus::MessageReader reader(method_call);
565 dbus::MessageWriter writer(dbus_response.get());
566
567 patchpanel::TerminaVmShutdownRequest request;
568 patchpanel::TerminaVmShutdownResponse response;
569
570 if (!reader.PopArrayOfBytesAsProto(&request)) {
571 LOG(ERROR) << "Unable to parse request";
572 writer.AppendProtoAsArrayOfBytes(response);
573 return dbus_response;
574 }
575
Garrick Evans51d5b552020-01-30 10:42:06 +0900576 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
577
578 writer.AppendProtoAsArrayOfBytes(response);
579 return dbus_response;
580}
581
582std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
583 dbus::MethodCall* method_call) {
584 LOG(INFO) << "Plugin VM starting up";
585
586 std::unique_ptr<dbus::Response> dbus_response(
587 dbus::Response::FromMethodCall(method_call));
588
589 dbus::MessageReader reader(method_call);
590 dbus::MessageWriter writer(dbus_response.get());
591
592 patchpanel::PluginVmStartupRequest request;
593 patchpanel::PluginVmStartupResponse response;
594
595 if (!reader.PopArrayOfBytesAsProto(&request)) {
596 LOG(ERROR) << "Unable to parse request";
597 writer.AppendProtoAsArrayOfBytes(response);
598 return dbus_response;
599 }
600
Garrick Evans08fb34b2020-02-20 10:50:17 +0900601 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900602 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900603 LOG(ERROR) << "Failed to start Plugin VM network service";
604 writer.AppendProtoAsArrayOfBytes(response);
605 return dbus_response;
606 }
607
608 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
609 if (!tap) {
610 LOG(DFATAL) << "TAP device missing";
611 writer.AppendProtoAsArrayOfBytes(response);
612 return dbus_response;
613 }
614
Garrick Evans51d5b552020-01-30 10:42:06 +0900615 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900616 dev->set_ifname(tap->host_ifname());
617 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900618 if (!subnet) {
619 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
620 writer.AppendProtoAsArrayOfBytes(response);
621 return dbus_response;
622 }
623 auto* resp_subnet = dev->mutable_ipv4_subnet();
624 resp_subnet->set_base_addr(subnet->BaseAddress());
625 resp_subnet->set_prefix_len(subnet->PrefixLength());
626
627 writer.AppendProtoAsArrayOfBytes(response);
628 return dbus_response;
629}
630
631std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
632 dbus::MethodCall* method_call) {
633 LOG(INFO) << "Plugin VM shutting down";
634
635 std::unique_ptr<dbus::Response> dbus_response(
636 dbus::Response::FromMethodCall(method_call));
637
638 dbus::MessageReader reader(method_call);
639 dbus::MessageWriter writer(dbus_response.get());
640
641 patchpanel::PluginVmShutdownRequest request;
642 patchpanel::PluginVmShutdownResponse response;
643
644 if (!reader.PopArrayOfBytesAsProto(&request)) {
645 LOG(ERROR) << "Unable to parse request";
646 writer.AppendProtoAsArrayOfBytes(response);
647 return dbus_response;
648 }
649
650 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900651
652 writer.AppendProtoAsArrayOfBytes(response);
653 return dbus_response;
654}
655
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900656std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
657 dbus::MethodCall* method_call) {
658 std::unique_ptr<dbus::Response> dbus_response(
659 dbus::Response::FromMethodCall(method_call));
660
661 dbus::MessageReader reader(method_call);
662 dbus::MessageWriter writer(dbus_response.get());
663
664 patchpanel::SetVpnIntentRequest request;
665 patchpanel::SetVpnIntentResponse response;
666
667 bool success = reader.PopArrayOfBytesAsProto(&request);
668 if (!success) {
669 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
670 // Do not return yet to make sure we close the received fd.
671 }
672
673 base::ScopedFD client_socket;
674 reader.PopFileDescriptor(&client_socket);
675
676 if (success)
677 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
678
679 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900680
681 writer.AppendProtoAsArrayOfBytes(response);
682 return dbus_response;
683}
684
685std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
686 dbus::MethodCall* method_call) {
687 std::unique_ptr<dbus::Response> dbus_response(
688 dbus::Response::FromMethodCall(method_call));
689
690 dbus::MessageReader reader(method_call);
691 dbus::MessageWriter writer(dbus_response.get());
692
693 patchpanel::ConnectNamespaceRequest request;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900694
695 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900696 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
697 // Do not return yet to make sure we close the received fd and
698 // validate other arguments.
Hugo Benichi7c342672020-09-08 09:18:14 +0900699 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
700 return dbus_response;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900701 }
702
Hugo Benichicc6850f2020-01-17 13:26:06 +0900703 base::ScopedFD client_fd;
704 reader.PopFileDescriptor(&client_fd);
705 if (!client_fd.is_valid()) {
706 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
Hugo Benichi7c342672020-09-08 09:18:14 +0900707 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
708 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900709 }
710
711 pid_t pid = request.pid();
712 {
713 ScopedNS ns(pid);
714 if (!ns.IsValid()) {
715 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900716 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
717 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900718 }
719 }
720
721 const std::string& outbound_ifname = request.outbound_physical_device();
722 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
723 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
724 << outbound_ifname;
Hugo Benichi7c342672020-09-08 09:18:14 +0900725 writer.AppendProtoAsArrayOfBytes(patchpanel::ConnectNamespaceResponse());
726 return dbus_response;
Hugo Benichicc6850f2020-01-17 13:26:06 +0900727 }
728
Hugo Benichi7c342672020-09-08 09:18:14 +0900729 auto response = ConnectNamespace(std::move(client_fd), request);
730 writer.AppendProtoAsArrayOfBytes(*response);
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900731 return dbus_response;
732}
733
Jie Jiang493cde42020-07-17 21:43:39 +0900734std::unique_ptr<dbus::Response> Manager::OnGetTrafficCounters(
735 dbus::MethodCall* method_call) {
736 std::unique_ptr<dbus::Response> dbus_response(
737 dbus::Response::FromMethodCall(method_call));
738
739 dbus::MessageReader reader(method_call);
740 dbus::MessageWriter writer(dbus_response.get());
741
742 patchpanel::TrafficCountersRequest request;
743 patchpanel::TrafficCountersResponse response;
744
745 if (!reader.PopArrayOfBytesAsProto(&request)) {
746 LOG(ERROR) << "Unable to parse TrafficCountersRequest";
747 writer.AppendProtoAsArrayOfBytes(response);
748 return dbus_response;
749 }
750
751 const std::set<std::string> devices{request.devices().begin(),
752 request.devices().end()};
753 const auto counters = counters_svc_->GetCounters(devices);
754 for (const auto& kv : counters) {
755 auto* traffic_counter = response.add_counters();
756 const auto& source_and_device = kv.first;
757 const auto& counter = kv.second;
758 traffic_counter->set_source(source_and_device.first);
759 traffic_counter->set_device(source_and_device.second);
760 traffic_counter->set_rx_bytes(counter.rx_bytes);
761 traffic_counter->set_rx_packets(counter.rx_packets);
762 traffic_counter->set_tx_bytes(counter.tx_bytes);
763 traffic_counter->set_tx_packets(counter.tx_packets);
764 }
765
766 writer.AppendProtoAsArrayOfBytes(response);
767 return dbus_response;
768}
769
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900770std::unique_ptr<dbus::Response> Manager::OnModifyPortRule(
771 dbus::MethodCall* method_call) {
772 std::unique_ptr<dbus::Response> dbus_response(
773 dbus::Response::FromMethodCall(method_call));
774
775 dbus::MessageReader reader(method_call);
776 dbus::MessageWriter writer(dbus_response.get());
777
778 patchpanel::ModifyPortRuleRequest request;
779 patchpanel::ModifyPortRuleResponse response;
780
781 if (!reader.PopArrayOfBytesAsProto(&request)) {
782 LOG(ERROR) << "Unable to parse ModifyPortRequest";
783 writer.AppendProtoAsArrayOfBytes(response);
784 return dbus_response;
785 }
786
Jason Jeremy Imanc28df852020-07-11 17:38:26 +0900787 response.set_success(ModifyPortRule(request));
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900788 writer.AppendProtoAsArrayOfBytes(response);
789 return dbus_response;
790}
791
Jie Jiang84966852020-09-18 18:49:05 +0900792void Manager::OnNeighborConnectedStateChanged(
793 int ifindex,
794 const shill::IPAddress& ip_addr,
795 NeighborLinkMonitor::NeighborRole role,
796 bool connected) {
797 if (!ip_addr.IsValid()) {
798 LOG(DFATAL) << "ip_addr is not valid";
799 return;
800 }
801
802 using SignalProto = NeighborConnectedStateChangedSignal;
803 SignalProto proto;
804 proto.set_ifindex(ifindex);
805 proto.set_ip_addr(ip_addr.ToString());
806 switch (role) {
807 case NeighborLinkMonitor::NeighborRole::kGateway:
808 proto.set_role(SignalProto::GATEWAY);
809 break;
810 case NeighborLinkMonitor::NeighborRole::kDNSServer:
811 proto.set_role(SignalProto::DNS_SERVER);
812 break;
813 case NeighborLinkMonitor::NeighborRole::kGatewayAndDNSServer:
814 proto.set_role(SignalProto::GATEWAY_AND_DNS_SERVER);
815 break;
816 default:
817 NOTREACHED();
818 }
819
820 dbus::Signal signal(kPatchPanelInterface,
821 kNeighborConnectedStateChangedSignal);
822 dbus::MessageWriter writer(&signal);
823 if (!writer.AppendProtoAsArrayOfBytes(proto)) {
824 LOG(ERROR) << "Failed to encode proto NeighborConnectedStateChangedSignal";
825 return;
826 }
827
828 dbus_svc_path_->SendSignal(&signal);
829}
830
Hugo Benichi7c342672020-09-08 09:18:14 +0900831std::unique_ptr<patchpanel::ConnectNamespaceResponse> Manager::ConnectNamespace(
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900832 base::ScopedFD client_fd,
Hugo Benichi7c342672020-09-08 09:18:14 +0900833 const patchpanel::ConnectNamespaceRequest& request) {
834 auto response = std::make_unique<patchpanel::ConnectNamespaceResponse>();
835
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900836 std::unique_ptr<Subnet> subnet =
837 addr_mgr_.AllocateIPv4Subnet(AddressManager::Guest::MINIJAIL_NETNS);
838 if (!subnet) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900839 LOG(ERROR) << "ConnectNamespace: exhausted IPv4 subnet space";
840 return response;
Hugo Benichie8758b52020-04-03 14:49:01 +0900841 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900842
Hugo Benichi7352ad92020-04-07 16:11:59 +0900843 // Dup the client fd into our own: this guarantees that the fd number will
844 // be stable and tied to the actual kernel resources used by the client.
845 base::ScopedFD local_client_fd(dup(client_fd.get()));
846 if (!local_client_fd.is_valid()) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900847 PLOG(ERROR) << "ConnectNamespace: failed to dup() client fd";
848 return response;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900849 }
850
Hugo Benichi7c342672020-09-08 09:18:14 +0900851 // Add the duped fd to the epoll watcher.
Hugo Benichi7352ad92020-04-07 16:11:59 +0900852 // TODO(hugobenichi) Find a way to reuse base::FileDescriptorWatcher for
853 // listening to EPOLLHUP.
854 struct epoll_event epevent;
855 epevent.events = EPOLLIN; // EPOLLERR | EPOLLHUP are always waited for.
856 epevent.data.fd = local_client_fd.get();
857 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_ADD,
858 local_client_fd.get(), &epevent) != 0) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900859 PLOG(ERROR) << "ConnectNamespace: epoll_ctl(EPOLL_CTL_ADD) failed";
860 return response;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900861 }
862
Hugo Benichi7c342672020-09-08 09:18:14 +0900863 const std::string ifname_id = std::to_string(connected_namespaces_next_id_);
864 const std::string netns_name = "connected_netns_" + ifname_id;
865 const std::string host_ifname = "arc_ns" + ifname_id;
866 const std::string client_ifname = "veth" + ifname_id;
867 if (!datapath_->StartRoutingNamespace(
868 request.pid(), netns_name, host_ifname, client_ifname,
869 subnet->BaseAddress(), subnet->PrefixLength(),
870 subnet->AddressAtOffset(0), subnet->AddressAtOffset(1),
871 addr_mgr_.GenerateMacAddress())) {
872 LOG(ERROR) << "ConnectNamespace: failed to setup datapath";
873 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL,
874 local_client_fd.get(), nullptr) != 0)
875 PLOG(ERROR) << "ConnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
876 return response;
877 }
878
879 // TODO(hugobenichi) The peer and host addresses are swapped in the response
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900880 // Prepare the response before storing ConnectNamespaceInfo.
Hugo Benichi7c342672020-09-08 09:18:14 +0900881 response->set_peer_ifname(client_ifname);
882 response->set_peer_ipv4_address(subnet->AddressAtOffset(0));
883 response->set_host_ifname(host_ifname);
884 response->set_host_ipv4_address(subnet->AddressAtOffset(1));
885 auto* response_subnet = response->mutable_ipv4_subnet();
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900886 response_subnet->set_base_addr(subnet->BaseAddress());
887 response_subnet->set_prefix_len(subnet->PrefixLength());
888
889 // Store ConnectNamespaceInfo
890 connected_namespaces_next_id_++;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900891 int fdkey = local_client_fd.release();
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900892 connected_namespaces_[fdkey] = {};
893 ConnectNamespaceInfo& ns_info = connected_namespaces_[fdkey];
894 ns_info.pid = request.pid();
Hugo Benichi33860d72020-07-09 16:34:01 +0900895 ns_info.netns_name = std::move(netns_name);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900896 ns_info.outbound_ifname = request.outbound_physical_device();
897 ns_info.host_ifname = std::move(host_ifname);
898 ns_info.client_ifname = std::move(client_ifname);
899 ns_info.client_subnet = std::move(subnet);
900
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900901 LOG(INFO) << "Connected network namespace " << ns_info;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900902
903 if (connected_namespaces_.size() == 1) {
904 LOG(INFO) << "Starting ConnectNamespace client fds monitoring";
905 CheckConnectedNamespaces();
906 }
Hugo Benichi7c342672020-09-08 09:18:14 +0900907
908 return response;
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900909}
910
911void Manager::DisconnectNamespace(int client_fd) {
912 auto it = connected_namespaces_.find(client_fd);
913 if (it == connected_namespaces_.end()) {
914 LOG(ERROR) << "No ConnectNamespaceInfo found for client_fd " << client_fd;
915 return;
916 }
917
Hugo Benichi7352ad92020-04-07 16:11:59 +0900918 // Remove the client fd dupe from the epoll watcher and close it.
919 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL, client_fd,
Hugo Benichie8758b52020-04-03 14:49:01 +0900920 nullptr) != 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900921 PLOG(ERROR) << "DisconnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900922 if (close(client_fd) < 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +0900923 PLOG(ERROR) << "DisconnectNamespace: close(client_fd) failed";
Hugo Benichi7352ad92020-04-07 16:11:59 +0900924
Hugo Benichi7c342672020-09-08 09:18:14 +0900925 datapath_->StopRoutingNamespace(it->second.netns_name, it->second.host_ifname,
926 it->second.client_subnet->BaseAddress(),
927 it->second.client_subnet->PrefixLength(),
928 it->second.client_subnet->AddressAtOffset(0));
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900929
930 LOG(INFO) << "Disconnected network namespace " << it->second;
931
932 // This release the allocated IPv4 subnet.
933 connected_namespaces_.erase(it);
934}
935
Hugo Benichi7352ad92020-04-07 16:11:59 +0900936// TODO(hugobenichi) Generalize this check to all resources created by
937// patchpanel on behalf of a remote client.
938void Manager::CheckConnectedNamespaces() {
939 int max_event = 10;
940 struct epoll_event epevents[max_event];
941 int nready = epoll_wait(connected_namespaces_epollfd_, epevents, max_event,
942 0 /* do not block */);
943 if (nready < 0)
944 PLOG(ERROR) << "CheckConnectedNamespaces: epoll_wait(0) failed";
945
946 for (int i = 0; i < nready; i++)
947 if (epevents[i].events & (EPOLLHUP | EPOLLERR))
948 DisconnectNamespace(epevents[i].data.fd);
949
950 if (connected_namespaces_.empty()) {
951 LOG(INFO) << "Stopping ConnectNamespace client fds monitoring";
952 return;
953 }
954
Qijiang Fan2d7aeb42020-05-19 02:06:39 +0900955 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Hugo Benichi7352ad92020-04-07 16:11:59 +0900956 FROM_HERE,
957 base::Bind(&Manager::CheckConnectedNamespaces,
Hugo Benichie8758b52020-04-03 14:49:01 +0900958 weak_factory_.GetWeakPtr()),
Hugo Benichi7352ad92020-04-07 16:11:59 +0900959 kConnectNamespaceCheckInterval);
960}
961
Jason Jeremy Imanc28df852020-07-11 17:38:26 +0900962bool Manager::ModifyPortRule(const patchpanel::ModifyPortRuleRequest& request) {
963 switch (request.proto()) {
964 case patchpanel::ModifyPortRuleRequest::TCP:
965 case patchpanel::ModifyPortRuleRequest::UDP:
966 break;
967 default:
968 LOG(ERROR) << "Unknown protocol " << request.proto();
969 return false;
970 }
971
972 switch (request.op()) {
973 case patchpanel::ModifyPortRuleRequest::CREATE:
974 switch (request.type()) {
975 case patchpanel::ModifyPortRuleRequest::ACCESS:
976 return firewall_.AddAcceptRules(request.proto(),
977 request.input_dst_port(),
978 request.input_ifname());
979 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
980 return firewall_.AddLoopbackLockdownRules(request.proto(),
981 request.input_dst_port());
982 case patchpanel::ModifyPortRuleRequest::FORWARDING:
983 return firewall_.AddIpv4ForwardRule(
984 request.proto(), request.input_dst_ip(), request.input_dst_port(),
985 request.input_ifname(), request.dst_ip(), request.dst_port());
986 default:
987 LOG(ERROR) << "Unknown port rule type " << request.type();
988 return false;
989 }
990 case patchpanel::ModifyPortRuleRequest::DELETE:
991 switch (request.type()) {
992 case patchpanel::ModifyPortRuleRequest::ACCESS:
993 return firewall_.DeleteAcceptRules(request.proto(),
994 request.input_dst_port(),
995 request.input_ifname());
996 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
997 return firewall_.DeleteLoopbackLockdownRules(
998 request.proto(), request.input_dst_port());
999 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1000 return firewall_.DeleteIpv4ForwardRule(
1001 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1002 request.input_ifname(), request.dst_ip(), request.dst_port());
1003 default:
1004 LOG(ERROR) << "Unknown port rule type " << request.type();
1005 return false;
1006 }
1007 default:
1008 LOG(ERROR) << "Unknown operation " << request.op();
1009 return false;
1010 }
1011}
1012
Garrick Evanse94a14e2019-11-11 10:32:13 +09001013void Manager::SendGuestMessage(const GuestMessage& msg) {
Garrick Evans96e03042019-05-28 14:30:52 +09001014 IpHelperMessage ipm;
1015 *ipm.mutable_guest_message() = msg;
Garrick Evans96e03042019-05-28 14:30:52 +09001016 adb_proxy_->SendMessage(ipm);
Garrick Evanse94a14e2019-11-11 10:32:13 +09001017 mcast_proxy_->SendMessage(ipm);
1018 nd_proxy_->SendMessage(ipm);
Garrick Evans96e03042019-05-28 14:30:52 +09001019}
1020
Garrick Evans4ac09852020-01-16 14:09:22 +09001021void Manager::StartForwarding(const std::string& ifname_physical,
1022 const std::string& ifname_virtual,
Garrick Evans4ac09852020-01-16 14:09:22 +09001023 bool ipv6,
1024 bool multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001025 if (ifname_physical.empty() || ifname_virtual.empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001026 return;
1027
1028 IpHelperMessage ipm;
1029 DeviceMessage* msg = ipm.mutable_device_message();
1030 msg->set_dev_ifname(ifname_physical);
Garrick Evans4ac09852020-01-16 14:09:22 +09001031 msg->set_br_ifname(ifname_virtual);
1032
1033 if (ipv6) {
1034 LOG(INFO) << "Starting IPv6 forwarding from " << ifname_physical << " to "
1035 << ifname_virtual;
1036
1037 if (!datapath_->AddIPv6Forwarding(ifname_physical, ifname_virtual)) {
1038 LOG(ERROR) << "Failed to setup iptables forwarding rule for IPv6 from "
1039 << ifname_physical << " to " << ifname_virtual;
1040 }
1041 if (!datapath_->MaskInterfaceFlags(ifname_physical, IFF_ALLMULTI)) {
1042 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1043 << ifname_physical;
1044 }
1045 if (!datapath_->MaskInterfaceFlags(ifname_virtual, IFF_ALLMULTI)) {
1046 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1047 << ifname_virtual;
1048 }
1049 nd_proxy_->SendMessage(ipm);
1050 }
1051
1052 if (multicast) {
1053 LOG(INFO) << "Starting multicast forwarding from " << ifname_physical
1054 << " to " << ifname_virtual;
1055 mcast_proxy_->SendMessage(ipm);
1056 }
1057}
1058
1059void Manager::StopForwarding(const std::string& ifname_physical,
1060 const std::string& ifname_virtual,
1061 bool ipv6,
1062 bool multicast) {
1063 if (ifname_physical.empty())
1064 return;
1065
1066 IpHelperMessage ipm;
1067 DeviceMessage* msg = ipm.mutable_device_message();
1068 msg->set_dev_ifname(ifname_physical);
1069 msg->set_teardown(true);
Taoyu Li7dca19a2020-03-16 16:27:07 +09001070 if (!ifname_virtual.empty()) {
1071 msg->set_br_ifname(ifname_virtual);
1072 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001073
1074 if (ipv6) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001075 if (ifname_virtual.empty()) {
1076 LOG(INFO) << "Stopping IPv6 forwarding on " << ifname_physical;
1077 } else {
1078 LOG(INFO) << "Stopping IPv6 forwarding from " << ifname_physical << " to "
1079 << ifname_virtual;
1080 datapath_->RemoveIPv6Forwarding(ifname_physical, ifname_virtual);
1081 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001082 nd_proxy_->SendMessage(ipm);
1083 }
1084
1085 if (multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001086 if (ifname_virtual.empty()) {
1087 LOG(INFO) << "Stopping multicast forwarding on " << ifname_physical;
1088 } else {
1089 LOG(INFO) << "Stopping multicast forwarding from " << ifname_physical
1090 << " to " << ifname_virtual;
1091 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001092 mcast_proxy_->SendMessage(ipm);
1093 }
1094}
1095
Taoyu Lia0727dc2020-09-24 19:54:59 +09001096void Manager::OnNDProxyMessage(const NDProxyMessage& msg) {
1097 LOG_IF(DFATAL, msg.ifname().empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001098 << "Received DeviceMessage w/ empty dev_ifname";
Taoyu Lia0727dc2020-09-24 19:54:59 +09001099 switch (msg.type()) {
1100 case NDProxyMessage::ADD_ROUTE:
1101 if (!datapath_->AddIPv6HostRoute(msg.ifname(), msg.ip6addr(), 128)) {
1102 LOG(WARNING) << "Failed to setup the IPv6 route for interface "
1103 << msg.ifname() << ", addr " << msg.ip6addr();
1104 }
1105 break;
1106 case NDProxyMessage::ADD_ADDR:
1107 if (!datapath_->AddIPv6Address(msg.ifname(), msg.ip6addr())) {
1108 LOG(WARNING) << "Failed to setup the IPv6 address for interface "
1109 << msg.ifname() << ", addr " << msg.ip6addr();
1110 }
1111 break;
1112 case NDProxyMessage::DEL_ADDR:
1113 datapath_->RemoveIPv6Address(msg.ifname(), msg.ip6addr());
1114 break;
1115 default:
1116 LOG(ERROR) << "Unknown NDProxy event " << msg.type();
1117 NOTREACHED();
Garrick Evans4ac09852020-01-16 14:09:22 +09001118 }
1119}
1120
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001121std::ostream& operator<<(std::ostream& stream,
1122 const Manager::ConnectNamespaceInfo& ns_info) {
1123 stream << "{ pid: " << ns_info.pid;
1124 if (!ns_info.outbound_ifname.empty()) {
1125 stream << ", outbound_ifname: " << ns_info.outbound_ifname;
1126 }
1127 stream << ", host_ifname: " << ns_info.host_ifname
1128 << ", client_ifname: " << ns_info.client_ifname
1129 << ", subnet: " << ns_info.client_subnet->ToCidrString() << '}';
1130 return stream;
1131}
1132
Garrick Evans3388a032020-03-24 11:25:55 +09001133} // namespace patchpanel