File: local_network_collector_impl.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 (448 lines) | stat: -rw-r--r-- 16,357 bytes parent folder | download | duplicates (3)
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
// Copyright 2019 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/sync_wifi/local_network_collector_impl.h"

#include "base/barrier_closure.h"
#include "base/uuid.h"
#include "chromeos/ash/components/dbus/shill/shill_service_client.h"
#include "chromeos/ash/components/network/network_event_log.h"
#include "chromeos/ash/components/network/network_handler.h"
#include "chromeos/ash/components/network/network_metadata_store.h"
#include "chromeos/ash/components/network/network_state.h"
#include "chromeos/ash/components/network/network_state_handler.h"
#include "chromeos/ash/components/sync_wifi/network_eligibility_checker.h"
#include "chromeos/ash/components/sync_wifi/network_identifier.h"
#include "chromeos/ash/components/sync_wifi/network_type_conversions.h"
#include "chromeos/services/network_config/public/mojom/network_types.mojom-shared.h"
#include "components/device_event_log/device_event_log.h"
#include "components/sync/protocol/wifi_configuration_specifics.pb.h"
#include "dbus/object_path.h"
#include "third_party/cros_system_api/dbus/shill/dbus-constants.h"

namespace ash::network_config {
namespace mojom = ::chromeos::network_config::mojom;
}

namespace ash::sync_wifi {

namespace {

dbus::ObjectPath GetServicePathForGuid(const std::string& guid) {
  const NetworkState* state =
      NetworkHandler::Get()->network_state_handler()->GetNetworkStateFromGuid(
          guid);
  if (!state) {
    return dbus::ObjectPath();
  }

  return dbus::ObjectPath(state->path());
}

bool IsAutoconnectUnspecified(
    const sync_pb::WifiConfigurationSpecifics& proto) {
  return !proto.has_automatically_connect() ||
         proto.automatically_connect() ==
             sync_pb::
                 WifiConfigurationSpecifics_AutomaticallyConnectOption_AUTOMATICALLY_CONNECT_UNSPECIFIED;
}

}  // namespace

LocalNetworkCollectorImpl::LocalNetworkCollectorImpl(
    network_config::mojom::CrosNetworkConfig* cros_network_config,
    SyncedNetworkMetricsLogger* metrics_recorder)
    : cros_network_config_(cros_network_config),
      metrics_recorder_(metrics_recorder) {
  cros_network_config_->AddObserver(
      cros_network_config_observer_receiver_.BindNewPipeAndPassRemote());

  // Load the current list of networks.
  OnNetworkStateListChanged();
}

LocalNetworkCollectorImpl::~LocalNetworkCollectorImpl() = default;

void LocalNetworkCollectorImpl::GetAllSyncableNetworks(
    ProtoListCallback callback) {
  if (!is_mojo_networks_loaded_) {
    after_networks_are_loaded_callback_queue_.push(
        base::BindOnce(&LocalNetworkCollectorImpl::GetAllSyncableNetworks,
                       weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
    return;
  }

  std::string request_guid = InitializeRequest();
  request_guid_to_list_callback_[request_guid] = std::move(callback);

  int count = 0;
  for (const network_config::mojom::NetworkStatePropertiesPtr& network :
       mojo_networks_) {
    if (!IsEligible(network)) {
      continue;
    }

    request_guid_to_in_flight_networks_[request_guid].insert(
        NetworkIdentifier::FromMojoNetwork(network));
    StartGetNetworkDetails(network.get(), request_guid);
    count++;
  }

  if (!count) {
    OnRequestFinished(request_guid);
  }
}

void LocalNetworkCollectorImpl::RecordZeroNetworksEligibleForSync() {
  if (has_logged_zero_eligible_networks_metric_) {
    return;
  }

  if (!is_mojo_networks_loaded_) {
    after_networks_are_loaded_callback_queue_.push(base::BindOnce(
        &LocalNetworkCollectorImpl::RecordZeroNetworksEligibleForSync,
        weak_ptr_factory_.GetWeakPtr()));
    return;
  }

  base::flat_set<NetworkEligibilityStatus>
      network_eligible_for_sync_status_codes;
  NetworkEligibilityStatus network_eligible_for_sync_status;
  for (const network_config::mojom::NetworkStatePropertiesPtr& network :
       mojo_networks_) {
    if (!network ||
        network->type != network_config::mojom::NetworkType::kWiFi) {
      continue;
    }
    network_eligible_for_sync_status = GetNetworkEligibilityStatus(
        network->guid, network->connectable,
        network->type_state->get_wifi()->hidden_ssid,
        network->type_state->get_wifi()->security, network->source,
        /*log_result=*/false);
    network_eligible_for_sync_status_codes.insert(
        network_eligible_for_sync_status);
  }
  metrics_recorder_->RecordZeroNetworksEligibleForSync(
      network_eligible_for_sync_status_codes);
  has_logged_zero_eligible_networks_metric_ = true;
}

void LocalNetworkCollectorImpl::GetSyncableNetwork(const std::string& guid,
                                                   ProtoCallback callback) {
  const network_config::mojom::NetworkStateProperties* network = nullptr;
  for (const network_config::mojom::NetworkStatePropertiesPtr& n :
       mojo_networks_) {
    if (n->guid == guid) {
      if (IsEligible(n)) {
        network = n.get();
      }

      break;
    }
  }

  if (!network) {
    std::move(callback).Run(std::nullopt);
    return;
  }

  std::string request_guid = InitializeRequest();
  request_guid_to_single_callback_[request_guid] = std::move(callback);

  StartGetNetworkDetails(network, request_guid);
}

std::optional<NetworkIdentifier>
LocalNetworkCollectorImpl::GetNetworkIdentifierFromGuid(
    const std::string& guid) {
  for (const network_config::mojom::NetworkStatePropertiesPtr& network :
       mojo_networks_) {
    if (network->guid == guid) {
      return NetworkIdentifier::FromMojoNetwork(network);
    }
  }
  return std::nullopt;
}

void LocalNetworkCollectorImpl::SetNetworkMetadataStore(
    base::WeakPtr<NetworkMetadataStore> network_metadata_store) {
  network_metadata_store_ = network_metadata_store;
}

std::string LocalNetworkCollectorImpl::InitializeRequest() {
  std::string request_guid = base::Uuid::GenerateRandomV4().AsLowercaseString();
  request_guid_to_complete_protos_[request_guid] =
      std::vector<sync_pb::WifiConfigurationSpecifics>();
  request_guid_to_in_flight_networks_[request_guid] =
      base::flat_set<NetworkIdentifier>();
  return request_guid;
}

bool LocalNetworkCollectorImpl::IsEligible(
    const network_config::mojom::NetworkStatePropertiesPtr& network) {
  if (!network || network->type != network_config::mojom::NetworkType::kWiFi) {
    return false;
  }

  const network_config::mojom::WiFiStatePropertiesPtr& wifi_properties =
      network->type_state->get_wifi();
  return IsEligibleForSync(network->guid, network->connectable,
                           wifi_properties->hidden_ssid,
                           wifi_properties->security, network->source,
                           /*log_result=*/true);
}

void LocalNetworkCollectorImpl::StartGetNetworkDetails(
    const network_config::mojom::NetworkStateProperties* network,
    const std::string& request_guid) {
  sync_pb::WifiConfigurationSpecifics proto;
  proto.set_hex_ssid(network->type_state->get_wifi()->hex_ssid);
  proto.set_security_type(
      SecurityTypeProtoFromMojo(network->type_state->get_wifi()->security));
  base::TimeDelta timestamp =
      network_metadata_store_->GetLastConnectedTimestamp(network->guid);
  proto.set_last_connected_timestamp(timestamp.InMilliseconds());
  cros_network_config_->GetManagedProperties(
      network->guid,
      base::BindOnce(&LocalNetworkCollectorImpl::OnGetManagedPropertiesResult,
                     weak_ptr_factory_.GetWeakPtr(), proto, request_guid));
}

void LocalNetworkCollectorImpl::OnGetManagedPropertiesResult(
    sync_pb::WifiConfigurationSpecifics proto,
    const std::string& request_guid,
    network_config::mojom::ManagedPropertiesPtr properties) {
  if (!properties) {
    NET_LOG(ERROR) << "GetManagedProperties failed.";
    OnNetworkFinished(NetworkIdentifier::FromProto(proto), request_guid);
    return;
  }
  proto.set_automatically_connect(AutomaticallyConnectProtoFromMojo(
      properties->type_properties->get_wifi()->auto_connect));
  proto.set_is_preferred(IsPreferredProtoFromMojo(properties->priority));

  // TODO(crbug/1128692): Restore support for the metered property when mojo
  // networks track the "Automatic" state.

  bool is_proxy_modified =
      network_metadata_store_->GetIsFieldExternallyModified(
          properties->guid, shill::kProxyConfigProperty);
  sync_pb::WifiConfigurationSpecifics_ProxyConfiguration proxy_config =
      ProxyConfigurationProtoFromMojo(properties->proxy_settings,
                                      /*is_unspecified=*/is_proxy_modified);
  proto.mutable_proxy_configuration()->CopyFrom(proxy_config);

  bool is_dns_externally_modified =
      network_metadata_store_->GetIsFieldExternallyModified(
          properties->guid, shill::kNameServersProperty);
  if (properties->static_ip_config &&
      properties->static_ip_config->name_servers &&
      (properties->source == network_config::mojom::OncSource::kUser ||
       !is_dns_externally_modified)) {
    proto.set_dns_option(
        sync_pb::WifiConfigurationSpecifics_DnsOption_DNS_OPTION_CUSTOM);
    for (const std::string& nameserver :
         properties->static_ip_config->name_servers->active_value) {
      proto.add_custom_dns(nameserver);
    }
  } else if (properties->source == network_config::mojom::OncSource::kDevice &&
             is_dns_externally_modified) {
    proto.set_dns_option(
        sync_pb::WifiConfigurationSpecifics_DnsOption_DNS_OPTION_UNSPECIFIED);
  } else {
    proto.set_dns_option(
        sync_pb::WifiConfigurationSpecifics_DnsOption_DNS_OPTION_DEFAULT_DHCP);
  }

  ShillServiceClient::Get()->GetWiFiPassphrase(
      GetServicePathForGuid(properties->guid),
      base::BindOnce(&LocalNetworkCollectorImpl::OnGetWiFiPassphraseResult,
                     weak_ptr_factory_.GetWeakPtr(), proto, request_guid),
      base::BindOnce(&LocalNetworkCollectorImpl::OnGetWiFiPassphraseError,
                     weak_ptr_factory_.GetWeakPtr(),
                     NetworkIdentifier::FromProto(proto), request_guid));
}

void LocalNetworkCollectorImpl::OnGetWiFiPassphraseResult(
    sync_pb::WifiConfigurationSpecifics proto,
    const std::string& request_guid,
    const std::string& passphrase) {
  proto.set_passphrase(passphrase);
  NetworkIdentifier id = NetworkIdentifier::FromProto(proto);
  request_guid_to_complete_protos_[request_guid].push_back(std::move(proto));
  OnNetworkFinished(id, request_guid);
}

void LocalNetworkCollectorImpl::OnGetWiFiPassphraseError(
    const NetworkIdentifier& id,
    const std::string& request_guid,
    const std::string& error_name,
    const std::string& error_message) {
  NET_LOG(ERROR) << "Failed to get passphrase for " << id.SerializeToString()
                 << " Error: " << error_name << " Details: " << error_message;

  OnNetworkFinished(id, request_guid);
}

void LocalNetworkCollectorImpl::OnNetworkFinished(
    const NetworkIdentifier& id,
    const std::string& request_guid) {
  request_guid_to_in_flight_networks_[request_guid].erase(id);

  if (request_guid_to_in_flight_networks_[request_guid].empty()) {
    OnRequestFinished(request_guid);
  }
}

void LocalNetworkCollectorImpl::OnRequestFinished(
    const std::string& request_guid) {
  DCHECK(request_guid_to_in_flight_networks_[request_guid].empty());

  if (request_guid_to_single_callback_[request_guid]) {
    std::vector<sync_pb::WifiConfigurationSpecifics>& list =
        request_guid_to_complete_protos_[request_guid];
    DCHECK(list.size() <= 1);
    std::optional<sync_pb::WifiConfigurationSpecifics> result;
    if (list.size() == 1) {
      result = list[0];
    }
    std::move(request_guid_to_single_callback_[request_guid]).Run(result);
    request_guid_to_single_callback_.erase(request_guid);
  } else {
    ProtoListCallback callback =
        std::move(request_guid_to_list_callback_[request_guid]);
    DCHECK(callback);
    std::move(callback).Run(request_guid_to_complete_protos_[request_guid]);
    request_guid_to_list_callback_.erase(request_guid);
  }

  request_guid_to_complete_protos_.erase(request_guid);
  request_guid_to_in_flight_networks_.erase(request_guid);
}

void LocalNetworkCollectorImpl::OnNetworkStateListChanged() {
  if (!NetworkHandler::Get()
           ->network_state_handler()
           ->IsProfileNetworksLoaded()) {
    is_mojo_networks_loaded_ = false;
    return;
  }

  cros_network_config_->GetNetworkStateList(
      network_config::mojom::NetworkFilter::New(
          network_config::mojom::FilterType::kConfigured,
          network_config::mojom::NetworkType::kWiFi,
          /*limit=*/0),
      base::BindOnce(&LocalNetworkCollectorImpl::OnGetNetworkList,
                     weak_ptr_factory_.GetWeakPtr()));
}

void LocalNetworkCollectorImpl::OnGetNetworkList(
    std::vector<network_config::mojom::NetworkStatePropertiesPtr> networks) {
  mojo_networks_ = std::move(networks);
  is_mojo_networks_loaded_ = true;
  while (!after_networks_are_loaded_callback_queue_.empty()) {
    std::move(after_networks_are_loaded_callback_queue_.front()).Run();
    after_networks_are_loaded_callback_queue_.pop();
  }
}

void LocalNetworkCollectorImpl::ExecuteAfterNetworksLoaded(
    base::OnceClosure callback) {
  if (is_mojo_networks_loaded_) {
    std::move(callback).Run();
    return;
  }

  after_networks_are_loaded_callback_queue_.push(std::move(callback));
}

void LocalNetworkCollectorImpl::FixAutoconnect(
    std::vector<sync_pb::WifiConfigurationSpecifics> protos,
    base::OnceClosure callback) {
  std::vector<std::string> guids_to_fix;
  for (const sync_pb::WifiConfigurationSpecifics& proto : protos) {
    // b/180854680 only affected networks with autoconnect unset/unspecified.
    if (!IsAutoconnectUnspecified(proto)) {
      continue;
    }

    network_config::mojom::NetworkStatePropertiesPtr network =
        GetNetworkFromProto(proto);
    if (!network) {
      // A synced network that is shared could have been removed by another user
      continue;
    }

    guids_to_fix.push_back(network->guid);
  }

  if (guids_to_fix.empty()) {
    std::move(callback).Run();
    return;
  }

  fix_autoconnect_callback_ =
      base::BarrierClosure(guids_to_fix.size(), std::move(callback));
  for (const std::string& guid : guids_to_fix) {
    cros_network_config_->GetManagedProperties(
        guid,
        base::BindOnce(&LocalNetworkCollectorImpl::EnableAutoconnectIfDisabled,
                       weak_ptr_factory_.GetWeakPtr()));
  }
}

void LocalNetworkCollectorImpl::OnFixAutoconnectComplete(
    bool success,
    const std::string& error) {
  if (!fix_autoconnect_callback_.is_null()) {
    fix_autoconnect_callback_.Run();
    return;
  }

  NOTREACHED();
}

network_config::mojom::NetworkStatePropertiesPtr
LocalNetworkCollectorImpl::GetNetworkFromProto(
    const sync_pb::WifiConfigurationSpecifics& proto) {
  auto id = NetworkIdentifier::FromProto(proto);
  network_config::mojom::NetworkStatePropertiesPtr network;
  for (const network_config::mojom::NetworkStatePropertiesPtr& n :
       mojo_networks_) {
    if (id == NetworkIdentifier::FromMojoNetwork(n)) {
      return n->Clone();
    }
  }
  return nullptr;
}

void LocalNetworkCollectorImpl::EnableAutoconnectIfDisabled(
    network_config::mojom::ManagedPropertiesPtr properties) {
  if (!properties ||
      properties->type != network_config::mojom::NetworkType::kWiFi) {
    OnFixAutoconnectComplete(/*success=*/true, /*error=*/std::string());
    return;
  }
  if (properties->type_properties->get_wifi()->auto_connect &&
      properties->type_properties->get_wifi()->auto_connect->active_value) {
    OnFixAutoconnectComplete(/*success=*/true, /*error=*/std::string());
    return;
  }

  NET_LOG(EVENT) << "Fixing autoconnect for "
                 << NetworkGuidId(properties->guid);
  auto config = network_config::mojom::ConfigProperties::New();
  config->type_config =
      network_config::mojom::NetworkTypeConfigProperties::NewWifi(
          network_config::mojom::WiFiConfigProperties::New());

  config->auto_connect = network_config::mojom::AutoConnectConfig::New(true);
  cros_network_config_->SetProperties(
      properties->guid, std::move(config),
      base::BindOnce(&LocalNetworkCollectorImpl::OnFixAutoconnectComplete,
                     weak_ptr_factory_.GetWeakPtr()));
}

}  // namespace ash::sync_wifi