blob: aeb1ff4d7d61bb1e040e76851a16b23c92aead83 [file] [log] [blame]
Jie Jiang31a0b4e2020-07-09 15:06:16 +09001// Copyright 2020 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
5#include "patchpanel/counters_service.h"
6
7#include <set>
8#include <string>
9#include <vector>
10
11namespace patchpanel {
12
13namespace {
14
15constexpr char kMangleTable[] = "mangle";
16
17} // namespace
18
19CountersService::CountersService(ShillClient* shill_client,
20 MinijailedProcessRunner* runner)
21 : shill_client_(shill_client), runner_(runner) {
22 // Triggers the callback manually to make sure no device is missed.
23 OnDeviceChanged(shill_client_->get_devices(), {});
24 shill_client_->RegisterDevicesChangedHandler(base::BindRepeating(
25 &CountersService::OnDeviceChanged, weak_factory_.GetWeakPtr()));
26}
27
28void CountersService::OnDeviceChanged(const std::set<std::string>& added,
29 const std::set<std::string>& removed) {}
30
31void CountersService::IptablesNewChain(const std::string& chain_name) {
32 // There is no straightforward way to check if a chain exists or not.
33 runner_->iptables(kMangleTable, {"-N", chain_name, "-w"},
34 false /*log_failures*/);
35 runner_->ip6tables(kMangleTable, {"-N", chain_name, "-w"},
36 false /*log_failures*/);
37}
38
39void CountersService::IptablesNewRule(std::vector<std::string> params) {
40 DCHECK_GT(params.size(), 0);
41 const std::string action = params[0];
42 DCHECK(action == "-I" || action == "-A");
43 params.emplace_back("-w");
44
45 params[0] = "-C";
46 if (runner_->iptables(kMangleTable, params, false /*log_failures*/) != 0) {
47 params[0] = action;
48 runner_->iptables(kMangleTable, params);
49 }
50
51 params[0] = "-C";
52 if (runner_->ip6tables(kMangleTable, params, false /*log_failures*/) != 0) {
53 params[0] = action;
54 runner_->ip6tables(kMangleTable, params);
55 }
56}
57
58} // namespace patchpanel