File: patchpanel_client.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (342 lines) | stat: -rw-r--r-- 11,741 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "chromeos/ash/components/dbus/patchpanel/patchpanel_client.h"

#include <utility>

#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/strings/strcat.h"
#include "base/task/single_thread_task_runner.h"
#include "chromeos/ash/components/dbus/patchpanel/fake_patchpanel_client.h"
#include "chromeos/ash/components/dbus/patchpanel/patchpanel_service.pb.h"
#include "dbus/bus.h"
#include "dbus/message.h"
#include "dbus/object_proxy.h"
#include "third_party/cros_system_api/dbus/patchpanel/dbus-constants.h"

namespace ash {
namespace {

PatchPanelClient* g_instance = nullptr;

void OnSignalConnected(const std::string& interface_name,
                       const std::string& signal_name,
                       bool success) {
  DCHECK_EQ(interface_name, patchpanel::kPatchPanelInterface);
  LOG_IF(DFATAL, !success) << "Failed to connect to D-Bus signal; interface: "
                           << interface_name << "; signal: " << signal_name;
}

// "Real" implementation of PatchPanelClient talking to the PatchPanel daemon
// on the Chrome OS side.
class PatchPanelClientImpl : public PatchPanelClient {
 public:
  PatchPanelClientImpl() = default;
  PatchPanelClientImpl(const PatchPanelClientImpl&) = delete;
  PatchPanelClientImpl& operator=(const PatchPanelClientImpl&) = delete;
  ~PatchPanelClientImpl() override = default;

  // PatchPanelClient overrides:
  void GetDevices(GetDevicesCallback callback) override {
    dbus::MethodCall method_call(patchpanel::kPatchPanelInterface,
                                 patchpanel::kGetDevicesMethod);
    dbus::MessageWriter writer(&method_call);

    patchpanel::GetDevicesRequest request;
    if (!writer.AppendProtoAsArrayOfBytes(request)) {
      LOG(ERROR) << "Failed to encode GetDevicesRequest proto";
      return;
    }

    patchpanel_proxy_->CallMethod(
        &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::BindOnce(&PatchPanelClientImpl::HandleGetDevicesResponse,
                       weak_factory_.GetWeakPtr(), std::move(callback)));
  }

  void NotifyAndroidInteractiveState(bool interactive) override {
    dbus::MethodCall method_call(
        patchpanel::kPatchPanelInterface,
        patchpanel::kNotifyAndroidInteractiveStateMethod);
    dbus::MessageWriter writer(&method_call);

    patchpanel::NotifyAndroidInteractiveStateRequest request;
    request.set_interactive(interactive);
    if (!writer.AppendProtoAsArrayOfBytes(request)) {
      LOG(ERROR) << "Failed to encode NotifyAndroidInteractiveState proto";
      return;
    }

    patchpanel_proxy_->CallMethod(&method_call,
                                  dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
                                  base::DoNothing());
  }

  void NotifyAndroidWifiMulticastLockChange(bool is_held) override {
    dbus::MethodCall method_call(
        patchpanel::kPatchPanelInterface,
        patchpanel::kNotifyAndroidWifiMulticastLockChangeMethod);
    dbus::MessageWriter writer(&method_call);

    patchpanel::NotifyAndroidWifiMulticastLockChangeRequest request;
    request.set_held(is_held);
    if (!writer.AppendProtoAsArrayOfBytes(request)) {
      LOG(ERROR) << "Failed to serialize NotifyAndroidWifiMulticastLockChange "
                    "request proto";
      return;
    }

    patchpanel_proxy_->CallMethod(&method_call,
                                  dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
                                  base::DoNothing());
  }

  void NotifySocketConnectionEvent(
      const patchpanel::SocketConnectionEvent& msg) override {
    dbus::MethodCall method_call(
        patchpanel::kPatchPanelInterface,
        patchpanel::kNotifySocketConnectionEventMethod);
    dbus::MessageWriter writer(&method_call);

    patchpanel::NotifySocketConnectionEventRequest request;
    *request.mutable_msg() = msg;

    if (!writer.AppendProtoAsArrayOfBytes(request)) {
      LOG(ERROR) << "Failed to serialize NotifySocketConnectionEvent "
                    "request proto";
      return;
    }

    patchpanel_proxy_->CallMethod(&method_call,
                                  dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
                                  base::DoNothing());
  }

  void NotifyARCVPNSocketConnectionEvent(
      const patchpanel::SocketConnectionEvent& msg) override {
    dbus::MethodCall method_call(
        patchpanel::kPatchPanelInterface,
        patchpanel::kNotifyARCVPNSocketConnectionEventMethod);
    dbus::MessageWriter writer(&method_call);

    patchpanel::NotifyARCVPNSocketConnectionEventRequest request;
    *request.mutable_msg() = msg;

    if (!writer.AppendProtoAsArrayOfBytes(request)) {
      LOG(ERROR) << "Failed to serialize NotifyARCVPNSocketConnectionEvent "
                    "request proto";
      return;
    }

    patchpanel_proxy_->CallMethod(&method_call,
                                  dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
                                  base::DoNothing());
  }

  void TagSocket(int socket_fd,
                 std::optional<int> network_id,
                 std::optional<VpnRoutingPolicy> vpn_policy,
                 TagSocketCallback callback) override {
    using patchpanel::TagSocketRequest;

    dbus::MethodCall method_call(patchpanel::kPatchPanelInterface,
                                 patchpanel::kTagSocketMethod);
    dbus::MessageWriter writer(&method_call);

    TagSocketRequest::VpnRoutingPolicy proto_vpn_policy =
        TagSocketRequest::DEFAULT_ROUTING;
    if (vpn_policy.has_value()) {
      switch (*vpn_policy) {
        case VpnRoutingPolicy::kRouteOnVpn:
          proto_vpn_policy = TagSocketRequest::ROUTE_ON_VPN;
          break;
        case VpnRoutingPolicy::kBypassVpn:
          proto_vpn_policy = TagSocketRequest::BYPASS_VPN;
          break;
      }
    }

    TagSocketRequest request;
    if (network_id.has_value()) {
      request.set_network_id(*network_id);
    }
    request.set_vpn_policy(proto_vpn_policy);

    if (!writer.AppendProtoAsArrayOfBytes(request)) {
      LOG(ERROR) << "Failed to serialize TagSocketRequest proto";
      base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
          FROM_HERE, base::BindOnce(std::move(callback), /*success=*/false));
      return;
    }
    writer.AppendFileDescriptor(socket_fd);

    patchpanel_proxy_->CallMethod(
        &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::BindOnce(&PatchPanelClientImpl::HandleTagSocketResponse,
                       weak_factory_.GetWeakPtr(), std::move(callback)));
  }

  void SetFeatureFlag(patchpanel::SetFeatureFlagRequest::FeatureFlag flag,
                      bool enabled) override {
    // SetFeatureFlag is be called on Chrome starts and it's very likely that
    // patchpanel D-Bus service is not ready at that time, so we want to use
    // WaitForServiceToBeAvailable() to post the task here. Note that if the
    // service is already ready, it will behave similar to a PostTask() so this
    // won't be harmful here.
    patchpanel_proxy_->WaitForServiceToBeAvailable(
        base::BindOnce(&PatchPanelClientImpl::SetFeatureFlagImpl,
                       weak_factory_.GetWeakPtr(), flag, enabled));
  }

  void SetFeatureFlagImpl(patchpanel::SetFeatureFlagRequest::FeatureFlag flag,
                          bool enabled,
                          bool patchpanel_service_ready) {
    if (!patchpanel_service_ready) {
      LOG(ERROR) << "Patchpanel service is not ready";
      return;
    }

    dbus::MethodCall method_call(patchpanel::kPatchPanelInterface,
                                 patchpanel::kSetFeatureFlagMethod);
    dbus::MessageWriter writer(&method_call);

    patchpanel::SetFeatureFlagRequest request;
    request.set_flag(flag);
    request.set_enabled(enabled);
    if (!writer.AppendProtoAsArrayOfBytes(request)) {
      LOG(ERROR) << "Failed to serialize SetFeatureFlag "
                    "request proto";
      return;
    }

    patchpanel_proxy_->CallMethod(&method_call,
                                  dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
                                  base::DoNothing());
  }

  void Init(dbus::Bus* bus) override {
    patchpanel_proxy_ = bus->GetObjectProxy(
        patchpanel::kPatchPanelServiceName,
        dbus::ObjectPath(patchpanel::kPatchPanelServicePath));
    ConnectToSignals();
  }

  void WaitForServiceToBeAvailable(
      dbus::ObjectProxy::WaitForServiceToBeAvailableCallback callback)
      override {
    patchpanel_proxy_->WaitForServiceToBeAvailable(std::move(callback));
  }

  void AddObserver(Observer* observer) override {
    observer_list_.AddObserver(observer);
  }

  void RemoveObserver(Observer* observer) override {
    observer_list_.RemoveObserver(observer);
  }

 private:
  void HandleGetDevicesResponse(GetDevicesCallback callback,
                                dbus::Response* dbus_response) {
    if (dbus_response == nullptr) {
      LOG(ERROR) << "Failed to receive the GetDevices response";
      std::move(callback).Run({});
      return;
    }

    patchpanel::GetDevicesResponse response;
    dbus::MessageReader reader(dbus_response);
    if (!reader.PopArrayOfBytesAsProto(&response)) {
      LOG(ERROR) << "Failed to parse GetDevices response proto";
      std::move(callback).Run({});
      return;
    }
    std::move(callback).Run(std::vector<patchpanel::NetworkDevice>(
        std::make_move_iterator(response.devices().begin()),
        std::make_move_iterator(response.devices().end())));
  }

  void HandleTagSocketResponse(TagSocketCallback callback,
                               dbus::Response* dbus_response) {
    if (dbus_response == nullptr) {
      LOG(ERROR) << "Failed to receive the TagSocket response";
      std::move(callback).Run({});
      return;
    }

    patchpanel::TagSocketResponse response;
    dbus::MessageReader reader(dbus_response);
    if (!reader.PopArrayOfBytesAsProto(&response)) {
      LOG(ERROR) << "Failed to parse TagSocketResponse proto";
      std::move(callback).Run({});
      return;
    }
    std::move(callback).Run(response.success());
  }

  void OnNetworkConfigurationChanged(dbus::Signal* signal) {
    for (auto& observer : observer_list_) {
      observer.NetworkConfigurationChanged();
    }
  }

  // Connects the dbus signals.
  void ConnectToSignals() {
    patchpanel_proxy_->ConnectToSignal(
        patchpanel::kPatchPanelInterface,
        patchpanel::kNetworkConfigurationChangedSignal,
        base::BindRepeating(
            &PatchPanelClientImpl::OnNetworkConfigurationChanged,
            weak_factory_.GetWeakPtr()),
        base::BindOnce(&OnSignalConnected));
  }

  // D-Bus proxy for the PatchPanel daemon, not owned.
  raw_ptr<dbus::ObjectProxy> patchpanel_proxy_ = nullptr;

  // List of observers for dbus signals.
  base::ObserverList<Observer> observer_list_;

  base::WeakPtrFactory<PatchPanelClientImpl> weak_factory_{this};
};

}  // namespace

PatchPanelClient::PatchPanelClient() {
  CHECK(!g_instance);
  g_instance = this;
}

PatchPanelClient::~PatchPanelClient() {
  CHECK_EQ(this, g_instance);
  g_instance = nullptr;
}

// static
void PatchPanelClient::Initialize(dbus::Bus* bus) {
  CHECK(bus);
  (new PatchPanelClientImpl())->Init(bus);
}

// static
void PatchPanelClient::InitializeFake() {
  new FakePatchPanelClient();
}

// static
void PatchPanelClient::Shutdown() {
  CHECK(g_instance);
  delete g_instance;
}

// static
PatchPanelClient* PatchPanelClient::Get() {
  return g_instance;
}

}  // namespace ash